0

Migrating from a MapActivity with a static SupportMapFragment in the layout to pure dynamic fragments.

The below code is the parent fragment. It contains a content view which I want to contain a dynamically created SupportMapFragment. The content happens to be a LinearLayout with the id: map_container.

    public class MapFragment extends android.support.v4.app.Fragment {

    private final LatLng NotHamburg = new LatLng(41.8236, -71.4222);
    protected GoogleMap _MAP;
    CustomMapFragment mapFragment;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_map, container, false);
        mapFragment = new CustomMapFragment();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.map_container, mapFragment).commit();

        newMarker();
        return rootView;
    }


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

    }


       //oh, user wants to see a new marker or remove some from inside the main fragment? Lets try...
    public void newMarker(){
        _MAP = mapFragment.getMap();
        _MAP.addMarker(new MarkerOptions().position(NotHamburg).title("NOTHamburg"));
    }   
}

The below code is my custom mapfragment

public class CustomMapFragment extends com.google.android.gms.maps.SupportMapFragment {


private final LatLng HAMBURG = new LatLng(40.8236, -71.4222);
private GoogleMap googleMap;

public static CustomMapFragment newInstance() {
    CustomMapFragment fragment = new CustomMapFragment();
    return fragment;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    googleMap = getMap();
    if (googleMap != null) {

        googleMap.addMarker(new MarkerOptions().position(HAMBURG).title("Hamburg"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
    }
}

At approximately line 17 of my fragment that contains the map, i get a null pointer. since the code works in the onactivitycreated() method of my actual MapFragment, the map must not be ready by line 17 in the onviewcreated method.

1 Answers1

0

The solution was to put anything map related from the Parent fragment in a handler with a small delay.

Interested in learning more about the life cycle and where a good place to start main loops and listeners in fragments. I guess I just have to be more wary of the UI thread and stuff.