我有一些信息存储为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气味?
提前致谢.
我在一个活动中有两种方法
private void save(String tag, final boolean isChecked)
{
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(tag, isChecked);
editor.commit();
}
private boolean load(String tag) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(tag, false);
}
Run Code Online (Sandbox Code Playgroud)
并且我不想使加载静态,以便从同一活动中的另一个静态方法中检索加载值.但是,当我尝试使load方法静态时,我当然会因为非静态引用而出错.我怎样才能做到这一点?
我尝试通过静态方法访问SharedPreferences而没有运气.
任何帮助将非常感激!