片段中的Android SharedPreferences

Mar*_*ark 77 android sharedpreferences android-fragments

我正在尝试阅读Fragment中的SharedPreferences.我的代码是我用来获取任何其他Activity的首选项.

     SharedPreferences preferences = getSharedPreferences("pref", 0);
Run Code Online (Sandbox Code Playgroud)

我收到错误

    Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper    
Run Code Online (Sandbox Code Playgroud)

我试图遵循这些链接,但没有运气通过静态方法静态SharedPreferences 访问SharedPreferences.谢谢你的任何解决方案.

Jug*_*aut 222

该方法getSharedPreferences是一个Context对象的方法,所以只调用一个getSharedPreferences Fragment将无法正常工作...因为它不是一个Context!(Activity是Context的扩展,所以我们可以从中调用getSharedPreferences).

所以你必须得到你的应用程序Context by

// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

  • 0类似于MODE_PRIVATE(如果在不是Context的扩展的类中使用,则为Context.MODE_PRIVATE,例如Fragment).这意味着只有相关应用才能访问首选项.您不应该使用WORLD_READABLE或WORLD_WRITEABLE,因为它们在API 17+中已被弃用,更不用说安全威胁了. (5认同)
  • @Subby no,明确地称之为"this"是绝对必要的.我是出于个人偏好而做的,因为我讨厌模糊的方法调用.唯一需要"this"的时候是当您在匿名内部类/接口中超出其范围时尝试访问父非静态对象时. (2认同)

Leo*_*eon 11

明确的答案对我不起作用,我不得不使用

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Run Code Online (Sandbox Code Playgroud)

编辑:

或者只是尝试删除this:

SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

  • 标记的答案对您不起作用,因为您正在访问默认的共享首选项.更好的设计是将您的偏好不是作为共享对象存储,而是存储在一个单独的私有空间中,这就是问题和答案. (6认同)

ed2*_*209 8

请注意,我上面的用户提供的答案是正确的.

SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
Run Code Online (Sandbox Code Playgroud)

但是,如果在onAttach调用之前尝试获取片段中的任何内容,则getActivity()将返回null.