Google Maps - Android App not load - null object reference

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

I am currently trying to develop an Android app with google Maps integration. At the moment I have difficulties to find the error, because the code is from the google site itself, except that it is a SupportMapFragment. If you know an actual tutorial with SupportMapFragment would also be great. Actual, because I think .getMap() is depreciated. If I should post the whole code, let me know (I am new in stackoverflow)

If try to use this code:

import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions;  public class MapsFragment extends SupportMapFragment implements OnMapReadyCallback {

where a function is:

    @Override      public void onResume() {     FragmentManager fragmentManager = getActivity().getSupportFragmentManager();     SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager             .findFragmentById(R.id.map);      supportMapFragment.getMapAsync(this); }

The error is: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference

The Fragment xml looks like this:

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

回答1:

Map fragment is acting up on Lollipop you may need this instead.

SupportMapFragment supportMapFragment; if (Build.VERSION.SDK_INT < 21) {     supportMapFragment = (SupportMapFragment) getActivity()         .getSupportFragmentManager().findFragmentById(R.id.map); } else {     supportMapFragment = (SupportMapFragment) getActivity()         .getChildFragmentManager().findFragmentById(R.id.map); } supportMapFragment.getMapAsync(this);


回答2:

It seems like you need to use the Fragment's SupportFragmentManager See the answer to this findFragmentById for SupportMapFragment returns null in Android Studio



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!