静态共享preferences [英] Static SharedPreferences

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

问题描述

我在一个活动的两种方法

I have two methods in an activity

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

}

和我wan't使负载的静态用于从相同的活性中的另一个静态方法检索负荷的值的宗旨。然而,当我试图使负载静态方法,我当然得到,因为非静态引用错误。我怎样才能使这项工作?

and I wan't to make the load static for the purposes of retrieving the values of load from another static method within the same activity. However, when I try to make the load method static, I of course get an error because of a non-static reference. How can I make this work?

我试过这个<一个href=\"http://stackoverflow.com/questions/3806051/accessing-shared$p$pferences-through-static-methods\">Accessing通过静态方法共享preferences 的,没有运气。

I tried this Accessing SharedPreferences through static methods with no luck.

任何帮助将是非常美联社preciated!

Any help would be much appreciated!

推荐答案

您可以保存和应用负载 - 宽共享preferences代替preFS专用于活动

You could save and load from Application-wide shared preferences instead of prefs private to the Activity:

private static boolean load(String tag) {
    SharedPreferences sharedPreferences = Context.getApplicationContext().getSharedPreferences("namespace", Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean(tag, false);
}

如果你这样做,确保你也存储的以同样的方式在preferences(通过使用 Context.getApplicationContext()。getShared preferences

If you do this, make sure you are also storing the preferences in the same way (by using Context.getApplicationContext().getSharedPreferences)

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

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