MsBao MsBao - 4 months ago 6x
Android Question

Data have been cached in Android 6 (SharePreferences)

I use SharePreference 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 sharepreference in Application:

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

Check to login:

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

Save if login success:

.putString("username", s.getLoggedInUser().getUsername())
.putString("profilePicUrl", s.getLoggedInUser().getProfilePicUrl())
.putString("pk", s.getLoggedInUser().getPk())

Clear when logout:



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