Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 242
MsBao Avatar asked Jan 17 '26 13:01

MsBao


1 Answers

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

like image 190
Gaurav Avatar answered Jan 20 '26 04:01

Gaurav