0

I've looked all over and can't seem to find an answer to my issue. For some reason the data saved in SharedPreferences reappears after switching activities. Why is my SharedPreferences still the exact same as it was before I cleared it and how can I fix this?

In first activity:

@Override
protected void onStop() {
    super.onStop();

    SharedPreferences sp = this.getSharedPreferences(TEMP_KEY, MODE_PRIVATE);
    Gson gson = new Gson();

    String objectJson = gson.toJson(object, Object.class);
    String activityJson = "FirstActivity";

    SharedPreferences.Editor editor = sp.edit();
    editor.putString(CONTINUE_KEY, objectJson);
    editor.putString(ACTIVITY_KEY, activityJson);
    editor.apply();
}

public void onClickSave() {

    Gson gson = new Gson();
    String objectJson = gson.toJson(object);
    SharedPreferences sp getSharedPreferences(SAVE_KEY, MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(object.getDate(), objectJson);
    editor.apply();

    SharedPreferences spTemp = this.getSharedPreferences(TEMP_KEY, MODE_PRIVATE);
    spTemp.edit().clear().apply();
    // go back to the main menu
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

Before the apply():

Debugger

After the apply():

Debugger

In Main Activity:

SharedPreferences sp = this.getSharedPreferences(TEMP_KEY, MODE_PRIVATE);

From main activity:

Debugger

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
John R.
  • 170
  • 8

3 Answers3

0

Save To Shared Preferences

SharedPreferences sp = getSharedPreferences("test" , MODE_PRIVATE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("hello1" , "hello11");
spEditor.putString("hello2" , "hello22");
spEditor.apply();

Clear From Shared Preferences

SharedPreferences sp1 = getSharedPreferences("test" , MODE_PRIVATE);
SharedPreferences.Editor spEditor1 = sp1.edit();
spEditor1.clear();
spEditor1.apply();

Get From Shared Preferences

SharedPreferences sp2 = getSharedPreferences("test" , MODE_PRIVATE);
String value =  sp2.getString("hello1" ,"noting");
Log.i("test_sp" , " == == ==" +value);
Ravi
  • 881
  • 1
  • 9
  • 23
0

First, you have different preference file name for getSharedPreferences(String name, int mode), in onStop() and onClickSave() methods:

// in onStop()
SharedPreferences sp = this.getSharedPreferences(TEMP_KEY, MODE_PRIVATE);

// in onClickSave()
SharedPreferences sp getSharedPreferences(SAVE_KEY, MODE_PRIVATE);

you need to use the same file name to access the same preference.

Second, onStop() is not always guaranteed to be called, so it's not a reliable method to save your preferences. Related answer: Is onStop() always preceded by onPause()

Third, always save the preference when you need to keep the value in it. Don't wait to save it later and hoping that you can depend on either onPause(), onStop(), or onDestroy(). Never assume that your application will gracely terminate by user or system.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
  • what's a better way to automatically save if `onPause()` and `onStop()` aren't always reliable? – John R. Mar 12 '19 at 04:30
  • No, only `onStop()` isnt' always guaranteed to be called. `onPause()` is guaranteed to be called. Please see this answer for details: https://stackoverflow.com/questions/19793194/is-onstop-always-preceded-by-onpause – ישו אוהב אותך Mar 12 '19 at 04:50
0

From Coordinating activities android documentation.

When one activity starts another, they both experience lifecycle transitions. The first activity stops operating and enters the Paused or Stopped state, while the other activity is created. In case these activities share data saved to disc or elsewhere, it's important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps with the process of stopping the first one.

The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process (app) and one is starting the other. Here's the order of operations that occur when Activity A starts Activity B:

  1. Activity A's onPause() method executes.

  2. Activity B's onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)

  3. Then, if Activity A is no longer visible on screen, its onStop() method executes.

This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another.

Back to your case, when you start MainActivity from FirstActivity.

  1. FirstActivity's onPause() method executes.

  2. MainActivity's onCreate(), onStart(), and onResume() methods execute in sequence. (MainActivity now has user focus.)

  3. Then, if FirstActivity is no longer visible on screen, its onStop() method executes.

When the code in onClickSave executes.

SharedPreferences spTemp = this.getSharedPreferences(TEMP_KEY, MODE_PRIVATE);
spTemp.edit().clear().apply();

At this time, TEMP_KEY prefs has been cleared. After MainActivity is visible on screen, FirstActivity will be no longer visible on screen, so its onStop() method executes.

SharedPreferences sp = this.getSharedPreferences(TEMP_KEY, MODE_PRIVATE);
Gson gson = new Gson();

String objectJson = gson.toJson(object, Object.class);
String activityJson = "FirstActivity";

SharedPreferences.Editor editor = sp.edit();
editor.putString(CONTINUE_KEY, objectJson);
editor.putString(ACTIVITY_KEY, activityJson);
editor.apply();

In this code you add two entries into TEMP_KEY prefs again. So when users click on a button in MainActivity, at that time the prefs size is 2 instead of 0 as you expected.

Why is my SharedPreferences still the exact same as it was before I cleared it?

This is predictable or expected behavior in Android. You can put a log in onCreate(), onStart(), onResume() method of MainActivity, then you can see TEMP_KEY prefs size at that time is always 0.

How can I fix this?

Do not add new entries into TEMP_KEY in onStop(), you should add in onPause() instead.

Son Truong
  • 13,661
  • 5
  • 32
  • 58