Reputation: 424
Need to restore markers which are stored in HashMap<String, Marker> markers;
when fragment is opened back from another activity.
This is what i tried:
HashMap<String, Marker> markers;
//..
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//..
this.markers = new HashMap<String, Marker>();
// Restoring the markers on configuration changes
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("markers")) {
markers = (HashMap<String, Marker>) savedInstanceState.getSerializable("markers");
if (markers != null) {
for (String key : markers.keySet()) {
Location location =
new Location(markers.get(key).getPosition().latitude, markers.get(key).getPosition().longitude);
addMarker(key, location);
}
}
}
}
return rootView;
}
public void addMarker(String key, Location location) {
//if (!key.equals(strUserID)) {
Marker marker = this.mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(location.latitude, location.longitude))
.icon(BitmapDescriptorFactory.defaultMarker()));
}
//...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("markers", markers);
}
I want to restore markers on fragment when fragment is resumed from the pause state from another activity. For Example: Activity A contains Fragment FA from which Activity B is called in foreground then on back-press again Fragment FA is opened:
Activity A (Fragment FA)(Markers shown on map and should store hashmap `onSaveInstanceState(Bundle outState)` when while activity B is called) ---> Activity B ---> (On Back-pressed restore markers from hashmap `if (savedInstanceState != null)`) Fragment FA.
Upvotes: 1
Views: 1944
Reputation: 16258
Please note that if:
A
doesn't call finish
when you switch to B
A
is configured to remain on back-stackFA
is configured to remain on back-stackThen when you switch to B
and then press back, A
and FA
will be popped from back-stack, which means that you get them in exactly the same state they were prior to switching to B
. In this case you don't need to do anything - your HashMap
is still valid and holds the correct content.
However, if the system need memory it might decide to destroy "back-stacked" Activity
and Fragment
instances, in which case it will call onSaveInstanceState
prior to destruction. If you now go back, then A
and FA
will be recreated, and will receive savedInstanceState
parameter containing saved state. Just use it to restore whatever you want.
Practically, (assuming that Marker
class implemented correctly) I think your code is fine, except one line in onCreateView
:
this.markers = new HashMap<String, Marker>();
If FA
is just popped from back-stack (and not re-created), this line causes you to loose the current state of HashMap
. I suggest you put this line in onCreate
, or simply initialize this map upon declaration:
private HashMap<String, Marker> markers = new HashMap<>();
Upvotes: 1