簡體   English   中英

Android SharedPreferences是否已清除?

[英]Android SharedPreferences gets cleared?

我和往常一樣使用共享首選項,但是最近在一個新應用程序中,緩存突然返回null,

這是讀/寫的方法

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;
}

然后在代碼中

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

在同一會話中使用

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

它確實會返回值,但是稍后退出應用程序並再次啟動它時,它返回null,一切似乎都很好

任何幫助,將不勝感激

您確定使用的上下文不是NULL嗎? 嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM