Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

android - SharedPreferences always get default value in my existing app but when created new app its ok

SharedPreferences doesn't work correct in one existing apps. I tried many different ways but still not working. Always get default values app start again.

  • It's working when I use same code in created new app.
  • It's working all of other existing apps.

Do you know why?

    String default_user = "Default_User";
    SharedPreferences pref = this.getSharedPreferences("TEST_SHAREDPREF", MODE_PRIVATE);
    String user = pref.getString("user", default_user);
    Log.d("SHARED CHECK", user);
    if (user.equals(default_user)) {
        SharedPreferences.Editor edit = pref.edit();
        edit.putString("user", "new_user");
        boolean ok = edit.commit();
        user = pref.getString("user", default_user);
        Log.d("SHARED WRITE", user);
        Toast.makeText(this, user + " Save process: " + ok, Toast.LENGTH_LONG).show();
    } else {
        Log.d("SHARED READ", user);
        Toast.makeText(this, "READ SharedPrefs: " + user, Toast.LENGTH_LONG).show();
    }

EDIT: log results

that block always return this for which is incorrect app and I don't know why

    //first run
    SHARED CHECK Default_User
    SHARED WRITE new_user

    //each time after first
    SHARED CHECK Default_User
    SHARED WRITE new_user

That block always return this for which are all apps

    //first run
    SHARED CHECK Default_User
    SHARED WRITE new_user

    //each time after first
    SHARED CHECK new_user
    SHARED READ new_user
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you call apply() or commit() the changes are first saved to the app's memory cache and then Android attempts to write those changes onto the disk. What is happening here is that your commit() call is failing on the disk but the changes are still made to the app's memory cache, as is visible in the source.

It is not enough to read the value from the SharedPreferences as that value might not reflect the true value that is on the disk but only that stored in the memory cache.

What you are failing to do is to check the boolean value returned from the commit() call, it is probably false for your problematic case. You could retry the commit() call a couple of times if false is returned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...