views:

95

answers:

2

Hello, 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.

+1  A: 

That's because in this case, act is an object that you just create. You have to leave android do that for you; getSharedPreferences is a method of Context, (Activity, Service and other classes extends from Context). So, you have to choices:

If the method is inside an activity or other kind of context

getApplicationContext().getSharedPreferences("foo", 0);

If the method is outside an activity or other kind of context

// you have to pass the context to it. In your case:
// this is inside a public class
public static SharedPreferences getSharedPreferences (Context ctxt) {
   return ctxt.getSharedPreferences("FILE", 0);
}

// and, this is in your activity
YourClass.getSharedPreferences(getApplicationContext());
Cristian
Thanks. My solution is based on your suggestion.
MyNameIsZero
+2  A: 

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. :-)
mreichelt
+1 Wow... love that idea.
Cristian
+1 for the Informative comment.
MyNameIsZero