I'm trying to store some data with SharedPreferences
method for store data:
public void storeSharedPreferences(String string) {
SharedPreferences sharedPreferences = getSharedPreferences("DATA",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("FRAGMENT",string);
editor.apply();
}
method for get data:
public String getSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences("DATA",MODE_PRIVATE);
String string = sharedPreferences.getString("FRAGMENT","ONE");
return string;
}
Method for fragment one and two:
public void buttonSelect(String select) {
if (select == "ONE") {
storeSharedPreferences("ONE");
fragment = new OneFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_process, fragment, "OneFragment").addToBackStack(null).commit();
}
if (select == "TWO") {
storeSharedPreferences("TWO");
fragment = new TwoFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_process, fragment, "TwoFragment").addToBackStack(null).commit();
}
}
And i call This method at first
buttonSelect(getSharedPreferences());
Everything is works fine for example when the user is in fragment two and exit the app
next time it will be start at fragment two
But the problem is use you close the app with menu(press menu button and clear all app) the next time you open the app nothing happen and seems this method never been called
buttonSelect(getSharedPreferences());
What can i do? Thanks
Initially, use editor.commit();
instead of editor.apply();
Next, the logic could be this:
buttonSelect
buttonSelect
will then load the specific fragment.Note: Don't forget to call the method buttonSelect
in the activity on app launch, either on onCreate()
or on onStart
Oh I totally forgot, string comparison in Java should be done via string.equals() function rather than double equals