I just begin developing with Android. The first challenge that I am facing now is how to save the fragment data when changing between fragment using a BottomNavigationController (Generated automatically by Android Studio)
I have tried using ViewModel, but since onDestroy() is being called every time when switches, the data is also lost. onSaveInstanceState() is not being called when switching the fragment neither.
Many methods or solutions I saw online use deprecated functions (Since I am just a beginner, I have no idea what is the new function being used right now)
I hope someone can help me with this! Thanks!
When a fragment is changed, it isn't destroyed, instead it is added to the backstack. All the instance variables remain there. You can retrieve the data in the onActivityCreated method. Here is an example:
public class ExampleFragment extends Fragment
{
private List<String> myData;
@Override public void onSaveInstanceState(final Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putSerializable("list", (Serializable) myData);
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
myData = (List<String>) savedInstanceState.getSerializable("list"); }
else { if (myData != null)
{ //returning from backstack}
else
{ myData = computeData(); } } } }
Edit :- You can also use shared preferences. Example :-
SharedPreferences shared ;
shared = getSharedPreferences("prefs", Context.MODE_PRIVATE);
shared.edit().putString("JSON",jsonString).commit();
Read more about storing and Retrieving data using Shared Preferences here : https://www-geeksforgeeks-org.cdn.ampproject.org/v/s/www.geeksforgeeks.org/shared-preferences-in-android-with-examples/amp/?amp_js_v=a3&_gsa=1&usqp=mq331AQFKAGwASA%3D#aoh=15850227567178&referrer=https%3A%2F%2Fwww.google.com&_tf=From%20%251%24s&share=https%3A%2F%2Fwww.geeksforgeeks.org%2Fshared-preferences-in-android-with-examples%2F