简体   繁体   中英

Android SharedPreferences gets cleared?

I'm using shared preferences as I always do, but recently in a new application the cache suddenly returns null,

here are the methods for read/write

public static void saveToSharedPreferences(Context mContext, String key, String value) {
    if (mContext != null) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, 0);
        if (mSharedPreferences != null)
            mSharedPreferences.edit().putString(key, value).commit();
    }
}

public static String readFromSharedPreferences(Context mContext, String key) {      
    if (mContext != null) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, 0);

        if (mSharedPreferences != null)
            return mSharedPreferences.getString(key, null);
    }
    return null;
}

then in the code

Utils.saveToSharedPreferences(getActivity(), mKey, mDATA);

in the same session when using

String mDATA = Utils.readFromSharedPreferences(getActivity(), mKey);

it does return the value, but later on when exiting the app and lauching it again, it returns null, everything seems to be fine

any help would be appreciated

Are you sure the Context you're using is not NULL? Try this:

SharedPreferences.Editor editor = mSharedPreferences.edit(); 
editor.putString(key, value); 
editor.commit(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM