为了账号安全,请及时绑定邮箱和手机立即绑定

通过静态方法访问SharedPreferences

通过静态方法访问SharedPreferences

千巷猫影 2019-11-14 15:25:35
我有一些信息存储为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代码气味吗?提前致谢。
查看完整描述

3 回答

?
绝地无双

TA贡献1946条经验 获得超4个赞

这是因为在这种情况下,这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 class

public static SharedPreferences getSharedPreferences (Context ctxt) {

   return ctxt.getSharedPreferences("FILE", 0);

}


// and, this is in your activity

YourClass.this.getSharedPreferences(YourClass.this.getApplicationContext());


查看完整回答
反对 回复 2019-11-14
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

我有一个类似的问题,我通过简单地将当前上下文传递给静态函数来解决了这个问题:


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;

将上下文存储为静态变量会导致问题,因为销毁类时,静态变量也会被破坏。当应用程序中断并且内存不足时,有时会发生这种情况。只需确保始终设置上下文,然后再尝试使用它,即使设置上下文的类被随机破坏了。


查看完整回答
反对 回复 2019-11-14
  • 3 回答
  • 0 关注
  • 806 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信