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

后端 未结 11 908
眼角桃花
眼角桃花 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 14:10

    Your code is right, the code works on any app very well, looks like that in some part of your app the shared preferences are been modified, the only way to find a solution is review all your code, because if this problem only happens on one app, it's somewhere on your app that the shared preferences are been modified, for good practices, you should have only one file class for the management of your preferences on that way you can comment or find usage for a method and you can find where the shared preferences was been modified.

    BTW the best way to store an user, password, or any account info is using Account Manager.

    For good practices you can see this sample PreferenceHelper class.

    public class PreferencesHelper {
    
    public static final String DEFAULT_STRING_VALUE = "default_value";
    
    /**
     * Returns Editor to modify values of SharedPreferences
     * @param context Application context
     * @return editor instance
     */
    private static Editor getEditor(Context context){
        return getPreferences(context).edit();
    }
    
    /**
     * Returns SharedPreferences object
     * @param context Application context
     * @return shared preferences instance
     */
    private static SharedPreferences getPreferences(Context context){
        String name = "YourAppPreferences";
        return context.getSharedPreferences(name,
                Context.MODE_PRIVATE);
    }
    
    /**
     * Save a string on SharedPreferences
     * @param tag tag
     * @param value value
     * @param context Application context
     */
    public static void putString(String tag, String value, Context context) {
        Editor editor = getEditor(context);
        editor.putString(tag, value);
        editor.commit();
    }
    
    /**
     * Get a string value from SharedPreferences
     * @param tag tag
     * @param context Application context
     * @return String value
     */
    public static String getString(String tag, Context context) {
        SharedPreferences sharedPreferences = getPreferences(context);
        return sharedPreferences.getString(tag, DEFAULT_STRING_VALUE);
    }}
    

提交回复
热议问题