开发者

Static SharedPreferences

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

}

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?

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

Any help would be much appreciated!


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜