【问题标题】:Google maps nullpointer [closed]谷歌地图空指针[关闭]
【发布时间】:2014-05-20 14:07:41
【问题描述】:

每次我尝试实例化地图时都会得到一个空指针。

我找到了很多关于它的文章,但是没有用。 该地图需要存在于另一个片段中。

这是我的代码:

public class ContactFragment extends Fragment {

private Contact contact = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    contact = Shared.dbRepo.contactsRepository.getFirst();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_price, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    GoogleMap map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.title(contact.getTitle());
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
    markerOptions.position(getLocation(contact.getAddress()));
    map.addMarker(markerOptions);

}

@Override
public void onResume() {
    super.onResume();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    MainActivity mainActivity = (MainActivity) activity;
    mainActivity.showActionBar();
}

private LatLng getLocation(String strAddress) {
    Geocoder coder = new Geocoder(getActivity().getApplicationContext());
    List<Address> address;

    try {
        address = coder.getFromLocationName(strAddress, 5);

        if (address == null) {
            Address location = address.get(0);

            return new LatLng(location.getLatitude(), location.getLongitude());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
}

XML:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:name="com.google.android.gms.maps.SupportMapFragment"/>

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="*"
    android:layout_margin="5dp">

    <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="3dp"
        android:paddingBottom="3dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/contact_address" />

        <TextView
            android:id="@+id/tv_contact_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:textColor="@color/text_gray"
            android:autoLink="map"
            android:text="@string/opening_hours" />

    </TableRow>

    <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="3dp"
        android:paddingBottom="3dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:autoLink="email"
            android:text="@string/contact_email" />

        <TextView
            android:id="@+id/tv_contact_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:textColor="@color/text_gray"
            android:text="@string/opening_hours" />

    </TableRow>

    <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="3dp"
        android:paddingBottom="3dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/contact_telephone" />

        <TextView
            android:id="@+id/tv_contact_telephone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:textColor="@color/text_gray"
            android:autoLink="phone"
            android:text="@string/opening_hours" />

    </TableRow>

    <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="3dp"
        android:paddingBottom="3dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/contact_website" />

        <TextView
            android:id="@+id/tv_contact_website"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:textColor="@color/text_gray"
            android:autoLink="web"
            android:text="@string/opening_hours" />

    </TableRow>
</TableLayout>
</LinearLayout>

编辑: 这是我得到的例外:

05-20 16:32:18.295    6663-6663/be.appmax.twentebad.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: be.appmax.twentebad.app, PID: 6663
    java.lang.NullPointerException
            at be.appmax.twentebad.app.fragments.ContactFragment.onViewCreated(ContactFragment.java:48)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:952)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5144)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
            at dalvik.system.NativeStart.main(Native Method)

这是第 48 行:

GoogleMap map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

【问题讨论】:

  • 试试我的答案@Ghost...
  • 第 50 行是什么???
  • 在帖子中添加了第 50 行
  • onViewCreated()的全部内容复制到onCreateView()..please..
  • 试一试,告诉我输出是什么......

标签: android google-maps android-fragments android-nested-fragment


【解决方案1】:

如果你正在使用

mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));

使用

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/map"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              class="com.google.android.gms.maps.SupportMapFragment"/>

您在 Java 类中使用了 SupportMapFragment,并且您在 xml 文件中使用了 MapFragment。这就是引发 NullPointerException 的原因...

编辑

SupportMapFragment mapFragment = ((SupportMapFragment) getActivity().getSupportFragmentManager()
            .findFragmentById(R.id.map)).getMap();

【讨论】:

  • 我修复了这个问题,但我添加了我现在得到的异常。
  • 我将整个代码添加到帖子中并编辑了异常
  • @Ghost 是您的 XML 中的地图片段中唯一的项目吗?如果是这样,我可以发布一个更详细的答案,而不是下面的答案。但是我不明白你为什么使用 getActivity()。
  • @Android-converter 我将完整的 XML 添加到我的帖子中。
【解决方案2】:

试试这条线:

mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getExtendedMap();

基本添加:.getExtendedMap();在你的片段行的最后

编辑: 如果你的 xml 是这样的:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:name="com.google.android.gms.maps.SupportMapFragment"/>

那么你在 onViewCreated 中的代码应该是:

mapFragment = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getExtendedMap();

我刚刚自己创建了一个示例应用程序来检查,它对我有用。当你到达(R.id.map))。 getExtendedMap() 不会有下拉选项;

【讨论】:

  • 从内存中使用 SupportMapFragment 时,您必须使用 getExtendedMap 而不是 getMap,这就是我的应用程序中的内容,我之前遇到过问题,getExtendedMap 为我修复了它
  • 我试过 getExtendedMap() 但它不存在。
  • 无法解决 getExtendedMap()
  • 你已经在你的类文件中导入了com.google.android.gms.maps.SupportMapFragment?
  • 在你的类的顶部,你应该扩展 FragmentActivity 而不仅仅是片段
【解决方案3】:

公共类 MapFragmentActivity 扩展 FragmentActivity {

GoogleMap map;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_map);
    googleMapMark();


}

private void googleMapMark() {
    // TODO Auto-generated method stub
    try {
        map = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapview)).getMap();
        Double lng = null, lat = null;

        Bundle b=getIntent().getExtras();

    if(map!=null){

        if(b!=null)
        {
            lat=b.getDouble("lat");
            Log.v("latitude in MapFragmentActivity","Latitude : " + lat);

            lng=b.getDouble("longitude");
            Log.v("longitude in MapFragmentActivity","Latitude : " + lng);
        }else
        {
            lat=23.0300;
            lng=72.5800;
            Log.v("Bundle is Null","Default lat long is set");
        }

        final LatLng mapPin = new LatLng(lat, lng);
        System.out.println("New Latitude:::-" + lat);
        System.out.println("New Longtitude:::-" + lng);

        map.addMarker(new MarkerOptions()
                .position(mapPin)
                .title("Latitude::-" + lat)
                .snippet("Longtitude::-" + lng)
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.malls)));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(mapPin, 15));
        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
    }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

【讨论】:

  • 我正在使用我所说的片段,所以我无法执行以下操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多