相关疑难解决方法(0)

通过静态方法访问SharedPreferences

我有一些信息存储为SharedPreferences.我需要从外部的Activity(从域模型类中)访问该信息.所以我在Activity中创建了一个静态方法,我只用它来获取共享首选项.

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

这是eclipse给我的信息:

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

我尝试使用Activity实例来解决这个问题,如下所示:

public static SharedPreferences getSharedPreferences () {
  Activity act = new Activity();
  return act.getSharedPreferences("FILE", 0);
}
Run Code Online (Sandbox Code Playgroud)

此代码提供null点异常.

有解决方法吗?我试图这样做,我会进入一个android-code气味?

提前致谢.

android static-methods sharedpreferences android-activity

31
推荐指数
4
解决办法
5万
查看次数