Hi I have a Fragment that loads a map fragment and fetches different data from a server. I want to save the state/instance of my fragments without destroying and replacing it. I do know about onSaveInstanceState(Bundle outState) but I did not understand how apply it in my case (I have read about the fragment cycle as well). Here is the code for the activity that interchanges(uses replace) each of the fragments when clicking on a menu item:
public class Menu extends Activity {
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
// map is here !!
fragment = new TestMap();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.resetTables();
Intent i = new Intent(getApplicationContext(), Login.class);
//Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayo
ut.closeDrawer(mDrawerList);
}
...
}
here is the the fragment for the map:
public class TestMap extends Fargment{
....
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity();
if(inst != null) {
// Remove the view from the parent
((ViewGroup)inst.getParent()).removeView(inst);
// Return it
return inst;
}
else{
final View myFragmentView = inflater.inflate(R.layout.activity_main, container, false);
try {
// Loading map and retrives locations from server
initilizeMap();
} catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
inst = myFragmentView;
return myFragmentView;
}
}
...
public void onDestroyView()
{
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
...
}
Hence, does anyone know how to save the keep a fragment that has already run at the beginnign without always replacing and destroying it each time I change fragments ? Thank you in advance.