Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap between Android maps v2 fragment and listfragment

I want to be able to switch between a list fragment and the map fragment by a user pushing an actionbar button. Currently I can swap between them just fine but I'm running into a null pointer when trying to get the actual GoogleMap object from the fragment. When I try and move the camera it doesn't move due to the GoogleMap object being null and skipping that code. I'm not sure if this has to due with the fact that I never actually create the Fragment from xml but rather am only using code? My code is as follows:

public class MapFragment extends SherlockMapFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = super.onCreateView(inflater, container, savedInstanceState);
        return root;
    }

}

    @Override
    public void swapFragments() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (listFragment.isVisible()) {
            sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
            transaction.replace(R.id.root, mapFragment);
        } else {
            sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
            transaction.replace(R.id.root, listFragment);
        }
        transaction.commit();
    }

    @Override
    public void setupMapFragment() {
        mapFragment = new MapFragment();
        mMap = mapFragment.getMap();
        if (mMap != null) {
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(BuzzbabaApplication.latitude,
                            BuzzbabaApplication.longitude), 14));
        }
    }
like image 869
egfconnor Avatar asked Oct 21 '22 17:10

egfconnor


1 Answers

I ran into this problem too. The problem is caused, as you mentioned, because you are loading the MapView dynamically. This means that the MapView has finished loading before the GoogleMap object loads.

A GoogleMap can only be acquired using getMap() when the underlying maps system is loaded and the underlying view in the fragment exists

(http://developer.android.com/reference/com/google/android/gms/maps/SupportMapFragment.html)

My solution was to create a map fragment in the XML. This means that when the View has finished loading, the GoogleMap object has also loaded and can be referenced.

like image 135
Rowan Freeman Avatar answered Nov 04 '22 02:11

Rowan Freeman