3

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!

Community
  • 1
  • 1
mikez
  • 160
  • 1
  • 15
  • I don't know what you mean by "no luck", but the second answer to the question you linked seems to be exactly what you need. – Gabriel Negut Jun 05 '11 at 06:23

1 Answers1

5

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)

loopj
  • 1,599
  • 1
  • 15
  • 12
  • In the beginning, i declared public static Context context. then in the onCreate method i initialized it to getApplicationContext(). then in my load and save methods i used context.getSharedPreferences etc etc. However, my first activity in my application references those methods (load and save) in another activity that hasn't yet been started (so on create is never called, and context returns a null value). How can i get these preferences without starting the activity? – mikez Jun 06 '11 at 21:28