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

后端 未结 11 922
眼角桃花
眼角桃花 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: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.

提交回复
热议问题