android - 通过静态方法访问 SharedPreferences

标签 android android-activity static-methods sharedpreferences

我有一些信息存储为 SharedPreferences。我需要从 Activity 外部访问该信息(从域模型类中)。因此,我在 Activity 中创建了一个静态方法,仅用于获取共享首选项。

这给我带来了一些问题,因为显然不可能从静态方法调用方法“getSharedPreferences”。

这是 eclipse 给我的信息:

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

我尝试通过使用 Activity 实例来解决此问题,如下所示:

public static SharedPreferences getSharedPreferences () {
  Activity act = new Activity();
  return act.getSharedPreferences("FILE", 0);
}

这段代码给出了一个空点异常。

有解决办法吗?我是否会因为尝试这样做而陷入 android-code-smell?

提前致谢。

最佳答案

克里斯蒂安的回答很好,但是如果您希望能够从任何地方访问您的共享偏好,那么正确的方法是:

  1. 创建 Application 的子类,例如public class MyApp extends Application { ...
  2. 设置android:name您的 <application> 的属性AndroidManifest.xml 中的标记以指向您的新类,例如android:name="MyApp" (因此该类被 Android 识别)
  3. 在应用实例的 onCreate() 方法中,将上下文(例如 this )保存到名为 app 的静态字段中并创建一个返回此字段的静态方法,例如getApp() .然后,您可以稍后使用此方法来获取应用程序的上下文,从而获取您的共享偏好。 :-)

关于android - 通过静态方法访问 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3806051/

相关文章:

android - 有没有类似string.xml的默认保存常量的地方?

java - 是否有理由不能拥有具有相同签名的静态和非静态方法?

android - 尝试访问应用程序中的文件时出错

android fragment addToBackStack(null) :how to add the same fragment to stack just one time?

android - 使用 OnTouch 事件在 Canvas 中选择和放置不同的形状

android - 如何从不扩展 Activity 的类中使用 setContentView(int)

android - Activity 和 JobIntentService 生命周期

java - 为什么 eclipse 告诉我静态方法引用 ClassName::staticMethod 应该为 "accessed in a static way"?

java - 从 actionPerformed 调用静态方法时出错,但从 static void main 调用则没有错误

android - 我需要一些帮助来理解 Android 应用程序开发中的异常