androidandroid-fragmentsfragmentsharedpreferencesandroid-sharedpreferences

Store data with SharedPreferences


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


Solution

  • Initially, use editor.commit(); instead of editor.apply();

    Next, the logic could be this:

    1. When the app is launched for the first time, create a shared preference and save the last fragment flag as 0. This would mean that the user is at the home fragment.
    2. Save the fragment number in the Shared Preferences whenever the user navigates through the app. SO this will keep on updating the last navigated fragment for the user.
    3. Whenever the app is launched next time, it will have a shared preference with last fragment number, fetch the last navigated fragment from the Shared Preferences and pass it to your method buttonSelect
    4. Your method 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