通过静态方法访问SharedPreferences

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


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


这是蚀给我的信息:


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代码气味吗?


提前致谢。


千巷猫影
浏览 808回答 3
3回答

绝地无双

这是因为在这种情况下,这act是您刚刚创建的对象。您必须让Android为您做到这一点;getSharedPreferences()是的方法Context,( Activity,Service和其它类从延伸Context)。因此,您必须做出选择:如果方法在活动或其他类型的上下文中:getApplicationContext().getSharedPreferences("foo", 0);如果方法在活动或其他类型的上下文之外:// you have to pass the context to it. In your case:// this is inside a public classpublic static SharedPreferences getSharedPreferences (Context ctxt) {   return ctxt.getSharedPreferences("FILE", 0);}// and, this is in your activityYourClass.this.getSharedPreferences(YourClass.this.getApplicationContext());

叮当猫咪

我有一个类似的问题,我通过简单地将当前上下文传递给静态函数来解决了这个问题:public static void LoadData(Context context){    SharedPreferences SaveData = context.getSharedPreferences(FILENAME, MODE_PRIVATE);    Variable = SaveData.getInt("Variable", 0);    Variable1 = SaveData.getInt("Variable1", 0);    Variable2 = SaveData.getInt("Variable2", 0);}由于您是从活动外部调用的,因此需要保存上下文:public static Context context;在OnCreate内部:context = this;将上下文存储为静态变量会导致问题,因为销毁类时,静态变量也会被破坏。当应用程序中断并且内存不足时,有时会发生这种情况。只需确保始终设置上下文,然后再尝试使用它,即使设置上下文的类被随机破坏了。
打开App,查看更多内容
随时随地看视频慕课网APP