Static SharedPreferences

2020-03-26 03:31发布

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!

1条回答
走好不送
2楼-- · 2020-03-26 04:08

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)

查看更多
登录 后发表回答