R
R
random2015-11-11 10:41:15
Android
random, 2015-11-11 10:41:15

Map fragment null pointer exception?

I have two tabs, in one tab google map V2. When I start to run it swears that here is null
mMap = mapFragment.getMap(); For example, I cannot use mMap in the inner class, it constantly swears at null.
It turns out that I can only use mMap in the onMapReady() method. What needs to be done so that it can be used in the whole class and even in others?

public class MapFragmentOne extends Fragment implements OnMapReadyCallback,
GoogleMap.OnMapClickListener{
 private static final int LAYOUT = R.layout.tab_one;
 private static View view;
 private static GoogleMap mMap;
 private SupportMapFragment mapFragment;

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LayoutInflater lf = getActivity().getLayoutInflater();
        view = lf.inflate(LAYOUT, container, false);

mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mapFragment == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map, mapFragment).commit();
        }
        mapFragment.getMapAsync(this);
        // Вот здесь null
          mMap = mapFragment.getMap();
        Log.d("MAP1", mMap + "");
        return view;
}

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // А вот здесь не null
        Log.d("MAP2", mMap + "");
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setBuildingsEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setIndoorEnabled(true);
        mMap.setOnMapClickListener(this);
    }

 @Override
    public void onMapClick(LatLng point) {
       if (mMap != null) {
             //Actions on clicks
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
razer89, 2015-11-11
@demon123

На этом этапе карта еще не готова. Для этого и существует метод onMapReady, в нем у вас гарантированно карта не будет равна null - используйте его. Если нужен доступ из других классов (что на мой взгляд очень некрасиво), можете реализовать свой listener, который будет срабатывать в методе onMapReady(), или сразу же, если карта уже доступна.

public class MapFragmentOne extends Fragment implements OnMapReadyCallback,
        GoogleMap.OnMapClickListener {
    private static final int LAYOUT = R.layout.tab_one;
    private static View view;
    private static GoogleMap mMap;
    private SupportMapFragment mapFragment;
    private OnGetMap listener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LayoutInflater lf = getActivity().getLayoutInflater();
        view = lf.inflate(LAYOUT, container, false);

        mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mapFragment == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map, mapFragment).commit();
        }
        mapFragment.getMapAsync(this);
        return view;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // А вот здесь не null
        Log.d("MAP2", mMap + "");
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setBuildingsEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setIndoorEnabled(true);
        mMap.setOnMapClickListener(this);
        if (listener != null) {
            listener.onGetMap(mMap);
        }
    }

    @Override
    public void onMapClick(LatLng point) {
        if (mMap != null) {
            //Actions on clicks
        }
    }

    public void getMap(OnGetMap listener) {
        if (mMap != null) {
            listener.onGetMap(mMap);
        } else {
            this.listener = listener;
        }
    }

    public interface OnGetMap {
        void onGetMap(GoogleMap map);
    }
}

В другом классе получаем так:
mapFragmentOne.getMap(new OnGetMap() {
            @Override
            public void onGetMap(GoogleMap map) {
                // do something with map
            }
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question