TAGS :Viewed: 2 - Published at: a few seconds ago

[ Android saving page data in fragment ]

I have a fragment that loads json data from server and display it in a list. my problem is that when I move to a different fragment on the same activity, that fragments data is being deleted. when I go back to that fragment all the data is empty, and it's loading again from the server. is there a way to keep the fragment alive in the background?

that's the code I use to switch fragments :

private void fragmentSwitch() {
    this.getFragmentManager().beginTransaction()
            .setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
            .replace(R.id.main_fragment_container, fragment)
            .commit();
}

Thanks a lot in advance.

Answer 1


I see 3 different options:

  1. Your activity keeps the data, so you can switch between fragments without loosing data. After your fragment is created you can call one method of the activity to get the data. For example you can create a method like getJsonData() in your activity and call it from your fragment (YourActivity)getActivity().getJsonData()

  2. You save data in SharedPreferences and access it from you fragment

  3. You save data in Database and access it from your fragment