1

I have an app with navigation drawer with Google Maps fragment and some other fragments. I'm creating the SupportMapFragment programmatically and putting it in my custom fragment_map layout in map container.

The problem is I have to add more than 2000+ markers to the map from database but do not want to fill them again every time the device got rotated. I thought the setRetainInstance(true) will solve the issue but it's not working — I'm getting a brand new map without markers and camera in 0, 0 position on orientation change. The sample apps are working fine with retained istance but they all are using FragmentActivity which is not my case. What is the problem with fragments here?

GoogleMapsFragment.java:

public class GoogleMapsFragment extends Fragment implements OnMapReadyCallback {

private SupportMapFragment mapFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_map, container, false);

    FragmentManager fm = getChildFragmentManager();
    mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        mapFragment.getMapAsync(this);
        mapFragment.setRetainInstance(true);
        fm.beginTransaction().add(R.id.map_cont, mapFragment).commit();
    }
    return rootView;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    googleMap.addMarker(new MarkerOptions().position(new LatLng(5, 5)));

    // a long code with map initialization and adding markers here
    // ...
}
}
Herman
  • 51
  • 3
  • I think it is because of nested fragment . Please refer this link http://stackoverflow.com/questions/14850573/cant-retain-nested-fragments – Krish Jan 04 '15 at 21:40

1 Answers1

0

By default when a configuration changes, such as the orientation, the entire activity is restarted, however you can prevent it from doing so by specifying when the activity can handle itself, this means you can tell the activity to not restart and instead call onConfigurationChanged

read more about it here : how can I save the fragment? when I rotate the screen

Community
  • 1
  • 1
steff_bdh
  • 1,108
  • 2
  • 15
  • 32