2

I have just one class where I need to access SharedPreferences:

public class MyUtils {

    public static String packageMe(Object input){
        // do stuff here
        // need SharedPreferences here
    }

    public static Object unpackageMe(String input){
        // do stuff here
        // need SharedPreferences here
    }
}

I tried this:

public class MyUtils extends Activity

But, as you know, I cannot access SharedPreferences from a static method.

I thought about passing in the context to the static methods, but that extends the number of classes out to four that I will need to modify, and the classes are already extending AsyncTask:

public class SomeClass01 extends AsyncTask {
    @Override
    protected Object doInBackground(Object[] params){
        MyUtils.packageMe(abc_123_object);
        // do stuff here
    }
}

So, I thought that maybe I could pass the context into those four classes. However, there are a couple dozen classes that I would need to modify that use those four classes, that in turn use that single class.

public class SomeTopClass extends FragmentActivity implements x, y, z {
    new SomeClass01.execute(abc_123_object);
    // do stuff here
}

I don't know if I want to be passing a context reference that deep into my code.

I saw here on StackOverflow about putting a reference to the SharedPreferences in my abc_123_object model, but there are quite a few objects I use (other than abc_123_object) and I don't want to have to jerry-rig so many classes.

So, is there a way for me to do this without modifying dozens of classes and passing context references all around my code, or am I stuck?

Thanks

Brian
  • 1,726
  • 2
  • 24
  • 62

2 Answers2

0

As Dusan mentioned, using an application class is an easy way to do this:

In your application class:

private static MyApplication sInstance = null;

private SharedPreferences mPrefs

public static MyApplication getApp()
{
    return sInstance;
}

public SharedPreferences getSharePreferences()
{
    return mPrefs;
}

in onCreate():

sInstance = this;
mPrefs = getSharedPreferences(PREF_FILE, MODE_PRIVATE);

Then in your code simply do:

MyApplication.getApp().getSharePreferences();

Your Application's onCreate() is guaranteed to be executed before any activity is created, so unless you are doing something really weird, it should be safe.

jt-gilkeson
  • 2,661
  • 1
  • 30
  • 40
0

Create static variable in your Application class.

public class MyApp extends Application{
    public static Context context;
@Override
    public void onCreate() {
    context = this;
    }
}

Then use it when you need.

public static String packageMe(Object input){
        // do stuff here
        // need SharedPreferences here
        // context = MyApp.context
    }
Fr099y
  • 734
  • 7
  • 15