通过静态方法访问 SharedPreferences [英] Accessing SharedPreferences through static methods

查看:18
本文介绍了通过静态方法访问 SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some information stored as SharedPreferences. I need to access that information from outsite an Activity (in from a domain model class). So I created a static method in an Activity which I only use to get the shared preferences.

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

This is giving me some problems, since apparently it is not possible to call the method "getSharedPreferences" from a static method.

这是日食给我的信息:

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

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

I tried to work around this by using an Activity instance, like this:

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

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

This code gives a null point exception.

有解决办法吗?尝试这样做我是否会陷入安卓代码的味道?

Is there a work-around? Am I going into an android-code-smell by trying to do this?

提前致谢.

推荐答案

那是因为在这种情况下,act 是您刚刚创建的对象.你必须让 Android 为你做这件事;getSharedPreferences()Context的一个方法,(Activity,Service等类继承自Context).因此,您必须做出选择:

That's because in this case, act is an object that you just create. You have to let Android do that for you; getSharedPreferences() is a method of Context, (Activity, Service and other classes extends from Context). So, you have to make your choice:

  • 如果方法在活动或其他类型的上下文中:

  • If the method is inside an activity or other kind of context:

getApplicationContext().getSharedPreferences("foo", 0);

  • 如果方法在活动或其他类型的上下文之外:

  • If the method is outside an activity or other kind of context:

    // 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());
    

  • 这篇关于通过静态方法访问 SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆