2016-03-04 158 views
2

//在一個片段sharedPreferences返回空值

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); 

SharedPreferences.Editor editor = preferences.edit(); 
editor.putString("aKeyString", "aValueString"); 
editor.apply() 

//If I try to log the just saved value the log is empty. Though I thought the apply(); committed that value to memory instantly and later to disc. So should be readable ? 

Log.d(TAG, preferences.getString("aKeyString","")); 
//nothing is logged to logcat at all. Not even a blank line. 

但是它在另一個片段,我需要閱讀的價值,而是返回null。

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); 
Log.d(TAG, "value: " + preferences.getString("aKeyString","")); 
//Logs out "value: null" 

爲什麼它爲空?我正在使用getDefaultSharedPreferences,這將確保我訪問正確的數據,並且出於同樣的原因getActivity().getApplicationContext()

對SO有關的喜好返回null類似問題的帖子被建議使用:

'申請();'而不是'commit();'我已經是。 或 他們建議使用'getDefaultSharedPreferences',而不是'getSharedPreferences',我也是。

爲什麼它是空的?

+0

嗨你爲什麼使用apply?爲什麼不提交? – Saveen

+2

@Saveen'apply()'比'commit()'快。 –

+0

不應該'getActivity()。getApplicationContext'是'getActivity()。getApplicationContext()'?錯字? –

回答

3

你這樣做是正確的方式,順便說一句奇怪的是,你說它顯示「空」,而你指定默認的空字符串值,根據javadoc應該是不可能的:

/** 
    * Retrieve a String value from the preferences. 
    * 
    * @param key The name of the preference to retrieve. 
    * @param defValue Value to return if this preference does not exist. 
    * 
    * @return Returns the preference value if it exists, or defValue. Throws 
    * ClassCastException if there is a preference with this name that is not 
    * a String. 
    * 
    * @throws ClassCastException 
    */ 
    @Nullable 
    String getString(String key, @Nullable String defValue); 

你確定它沒有在這裏拋出異常,並解釋爲什麼你看不到日誌行?

我建議你使用

布爾提交();

並檢查返回值。不幸的是apply方法會將其更改提交到內存中,但會啓動對磁盤的異步提交,並且不會通知您有任何失敗。

+0

把代碼是一個if語句檢查editor.commit();布爾值,它的作品。不知道爲什麼?不會是模擬器的問題嗎? – RyanTCB

4

我認爲你應該使用活動的情況下,不getApplicationContext()

他們兩人都是語境的情況下,但應用程序實例綁定到應用程序的生命週期,而活動實例綁定到活動的生命週期。因此,他們可以訪問有關應用程序環境的不同信息。

你可以得到的片段內相關活動的情況下,例如像:

private Context ctx; 

@Override 
public void onAttach(Context context) { 
super.onAttach(context); 
ctx = context; 
} 

然後在你需要它做的事:

preferences = PreferenceManager.getDefaultSharedPreferences(ctx); 
-1

使用這個代碼

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); 

SharedPreferences.Editor編輯= preferences.edit();

editor.putString(「aKeyString」,「aValueString」); editor.commite()