Search code examples
androidsharedpreferencesandroid-sharedpreferences

Data have been cached in Android 6 (SharedPreferences)


I use SharedPreference to save username after user login to my app and clear it if user logout.

I will check that value when start app, if that value null user need login to use.

However when I check with android 6.0:

Login (save username - Toast show not null) > Logout (remove username - Toast show null) > Remove App > Reinstall app > StartApp (not login - Toast show not null, this value is user that used => issue)

This issue no occur with android < 6.0

Here is my code:

init sharedpreference in Application:

public static SharedPreferences getPref() {
    return mInstance.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}

Check to login:

if (App.getPref().getString("username", null) == null){
   //Login
}

Save if login success:

                App.getPref().edit()
                                .putString("username", s.getLoggedInUser().getUsername())
                                .putString("profilePicUrl", s.getLoggedInUser().getProfilePicUrl())
                                .putString("pk", s.getLoggedInUser().getPk())
                                .apply();

Clear when logout:

   App.getPref().edit().clear().apply();

Solution

  • This is because of Automatic Backups. introduced in Marshmallow .

    It will take your data backup and used that backup at the time of reinstall .

    If you want to turn off it from settings -> Backup & reset -> automatic restore

    enter image description here

    But for your app I suggest make the shared pref.

    with key "username" to null at the time of logout and commit.

    or Simply make

    android:allowBackup="false" in your Manifest