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

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

问题描述

我的共享preferences存储的一些信息。我需要从(从领域模型类)访问outsite的活动信息。所以,我创建了一个活动,我只用它来获取共享preferences的静态方法。

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.

这是给我一些问题,因为显然它不可能调用从静态方法的方法getShared preferences。

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

这里的消息日食是给我:

Here's the message eclipse is giving me:

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

我试图解决这个通过使用活动实例,像这样的:

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);
}

这code给出零点例外。

This code gives a null point exception.

有一个变通?我是不是要去参加一个android- code-气味试图做到这一点?

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

在此先感谢。

推荐答案

这是因为在这种情况下,的行为是您只需创建一个对象。你必须让机器人为你做的; getShared preferences()上下文的方法,(活动服务和其他类从上下文扩展)。所以,你必须做出选择:

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

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

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