2012-07-31 21 views
62

Fragment içindeki SharedPreferences'ı okumaya çalışıyorum. Kodum, başka herhangi bir Etkinlikte tercih almak için kullandığım şeydir.Fragmandaki Android SharedPreferences

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

hata

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

Ben bu bağlantıları takip etmeye çalıştım ama hiçbir şans Accessing SharedPreferences through static methods ve Static SharedPreferences ile gelmiş olsun. Herhangi bir çözüm için teşekkür ederim.

cevap

176

getSharedPreferences yöntemi, Context nesnesinin bir yöntemidir, bu nedenle yalnızca Fragment'dan getSharedPreferences çağrısı işe yaramaz ... çünkü bu bir Bağlam değil! (Etkinlik, Bağlamın bir uzantısıdır, bu yüzden getSharedPreferences'ı bundan arayabiliriz).

Demek bana yukarıdaki kullanıcı tarafından sağlanan bu yanıt doğrudur dikkatli bir not olarak

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

getSharedPreferences ("pref", 0); Sıfır (0) özel/kamu ne demektir? – Kailas

+0

@Kailas doğru, mod, yani WORLD_READABLE ect. http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int) – Jug6ernaut

+0

paylaşılan tercihleri ​​hangi modda kullandığımı yalnızca bu uygulama tarafından erişilemez başka bir uygulama yok Paylaşılan tercihler değerlerini oku/yaz? – Kailas

4

tarafından Uygulamalarınız Bağlam almak zorunda. Eğer onAttach önce fragmanında şey elde denerseniz

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

Ancak boş dönecektir() getActivity denir.

+1

ve etkinliğe göre Etkinliği başlatılıncaya kadar etkinlik başlatılmaz ... – hotzen

9

işaretli cevap benim için işe yaramadı, ben kullanmak zorunda

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

DÜZENLEME:

Ya da sadece this kaldırmayı deneyin:

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

İşaretli yanıt sizin için çalışmadı çünkü varsayılan paylaşılan tercihlere erişiyorsunuz. Daha iyi bir tasarım, tercihlerinizi paylaşılan bir nesne olarak değil, ayrı ve özel bir alanda saklamaktır; – zeeshan

0

Sen SharedPrefences yapabilirsiniz gibi onAttach yönteminin parçası:

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