2012-07-31 39 views
62

我正在嘗試讀取Fragment內部的SharedPreferences。我的代碼就是我用來在其他任何Activity中獲取首選項的代碼。片段中的Android SharedPreferences

 SharedPreferences preferences = getSharedPreferences("pref", 0); 

我得到錯誤

Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper  

我試圖按照這些鏈接,但沒有運氣Accessing SharedPreferences through static methodsStatic SharedPreferences。感謝您提供任何解決方案。

回答

176

方法getSharedPreferencesContext對象的一個​​方法,所以從Fragment只是打電話getSharedPreferences將無法正常工作...因爲它不是一個上下文! (Activity是Context的擴展,所以我們可以從它調用getSharedPreferences)。

所以,你必須通過

// this = your fragment 
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE); 
+1

getSharedPreferences( 「期望」,0);零(0)是指什麼私人/公共? – Kailas 2013-10-22 07:25:21

+0

@Kailas正確,模式,即WORLD_READABLE等。 http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,int) – Jug6ernaut 2013-10-22 22:25:42

+0

什麼類型的模式我使用的共享首選項只有該應用程序訪問沒有其他應用程序讀取/寫入共享首選項值? – Kailas 2013-10-23 06:55:10

4

,讓您的應用程序上下文作爲一個值得注意的問題由用戶在我上面提供這個答案是正確的。

SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0); 

然而,如果試圖在onAttach之前的片段得到任何東西被稱爲getActivity()將返回null。

+1

並且活動未完全初始化,直到調用onActivityCreated爲止... – hotzen 2014-09-14 10:46:14

9

的顯着答案並沒有爲我工作,我不得不使用

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 

編輯:

或者只是嘗試刪除this

SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE); 
+3

標記的答案對您無效,因爲您正在訪問默認的共享首選項。更好的設計是將您的偏好不作爲共享對象存儲,而是存儲在單獨的私人空間中,這就是問題和答案。 – zeeshan 2014-11-10 15:48:04

0

可以使SharedPrefencesonAttach這樣的片段的方法:

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    SharedPreferences preferences = context.getSharedPreferences("pref", 0); 
}