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

后端 未结 11 896
眼角桃花
眼角桃花 2020-12-16 13:18

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\
相关标签:
11条回答
  • 2020-12-16 13:43

    Instead of using edit.commit();, you should use edit.apply();. Apply will update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.

    Source - Also read detailed difference between commit() and apply() in this SO Post.

    The "Source" post referenced above also states pretty much the same problem and switching to apply() seems to have resolved the issue there.

    Problem statement in the referenced post:

    The problem is that when I am accessing this values, it is not returning updated values, it gives me a value of SharedPreferences.

    But when I am confirming the data in XML file ,the data updated in that.

    PS: And the reason that the same code block is not working on this one app and working on all other apps could also be that you are either using the block at different places or updating the value somewhere else too.

    0 讨论(0)
  • 2020-12-16 13:44

    For saving and retrieving data from SharedPrefrence create a util type methods in your Utility class:

    Below I have given code snippet for both the methods i.e for saving and retrieving SharedPrefrence data:

       public class Utility {        
    
        public static void putStringValueInSharedPreference(Context context, String key, String value) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
        }
    
    
        public static String getStringSharedPreference(Context context, String param) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(param, "");
       }
    }
    

    Now you just need to call Utility.putStringValueInSharedPreference(Activity_Context,KEY,VALUE); to put data in prefrence and Utility.getStringSharedPreference(Activity_Context,KEY); to get value from prefrence. This methodology reduces chances of error; May this will be helpful for you.

    0 讨论(0)
  • 2020-12-16 13:45

    One thing you could try is to get a new SharedPreference instance after committing and see what happens:

    SharedPreferences pref = this.getSharedPreferences("test", MODE_PRIVATE);
    String user = pref.getString("user", default_user);
    if (user.equals(default_user)) {
        pref.edit().putString("user", "new_user").commit();
        SharedPreferences newPref = this.getSharedPreferences("test", MODE_PRIVATE);
        user = newPref.getString("user", default_user);
    }
    

    Your editor is committing a new preference map into disk, but it is possible that the old SharedPreference instance is not notified of the change.

    0 讨论(0)
  • 2020-12-16 13:54

    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.

    0 讨论(0)
  • 2020-12-16 13:54

    Don't know if this is correct or not, but you can implement a Shared preference change listener and you can log in that and check if the shared preference is not called again in any other class, which is again setting the value to Default user.

    I Mean you got to make sure that there is no other code resetting the value of user.

    0 讨论(0)
  • 2020-12-16 14:00

    I used the below code pattern in one of my app and I always get the latest value stored in SharedPreferences. Below is the edited version for your problem:

    public class AppPreference
            implements
            OnSharedPreferenceChangeListener {
    
        private static final String USER         = "User";
        private static final String DEFAULT_USER = "Default_User";
    
        private Context mContext;
        private String mDefaultUser;
    
        private SharedPreferences mPref;
        private static AppPreference mInstance;
    
        /**
         * hide it.
         */
        private AppPreference(Context context) {
            mContext = context;
            mPref = PreferenceManager.getDefaultSharedPreferences(context);
            mPref.registerOnSharedPreferenceChangeListener(this);
            reloadPreferences();
        }
    
        /**
         * @param context
         * @return single instance of shared preferences.
         */
        public static AppPreference getInstance(Context context) {
            return mInstance == null ?
                    (mInstance = new AppPreference(context)) :
                    mInstance;
        }
    
        /**
         * @return value of default user
         */
        public String getDefaultUser() {
            return mDefaultUser;
        }
    
        /**
         * Set value for default user
         */
        public void setDefaultUser(String user) {
            mDefaultUser = user;
            mPref.edit().putString(USER, mDefaultUser).apply();
        }
    
        /**
         * Reloads all values if preference values are changed.
         */
        private void reloadPreferences() {
            mDefaultUser = mPref.getString(USER, DEFAULT_USER);
            // reload all your preferences value here
        }
    
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            reloadPreferences();
        }
    }
    

    You can set the value as below in your activity:

    AppPreference.getInstance(this).setDefaultUser("user_value");
    

    To get the updated value for saved user, use below code:

    String user = AppPreference.getInstance(this).getDefaultUser();
    

    Hope this solution will fix the problem you are facing.

    0 讨论(0)
提交回复
热议问题