Accessing SharedPreferences through static methods

MyName picture MyName · Sep 27, 2010 · Viewed 49.9k times · Source

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.

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

This code gives a null point exception.

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

Thanks in advance.

Answer

mreichelt picture mreichelt · Sep 27, 2010

Cristian's answer is good, but if you want to be able to access your shared preferences from everywhere the right way would be:

  1. Create a subclass of Application, e.g. public class MyApp extends Application {...
  2. Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name="MyApp" (so the class is recognized by Android)
  3. In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp(). You then can use this method later to get a context of your application and therefore get your shared preferences. :-)