1

I need to store some data in the SharedPreferences in a class derived from Runnable.

It seems like there is no way to get hands on it without a context. For example the following will need a context object which is not available to the Runnable instance.

PreferenceManager.getDefaultSharedPreferences(Context context)

Is there any way to make it work in the Runnable or should I just go with the DB for all the preferences.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Vahid
  • 1,829
  • 1
  • 20
  • 35
  • Have you tried one of [these](http://stackoverflow.com/questions/3875391/context-inside-a-runnable) suggestions? – Andrea Dusza Dec 31 '15 at 01:03
  • Yeah. They suggest declaring the runnable inside an activity and use a local variable for the context. I prefer not to do that as I need my runnable to be reusable in other activities. Could I ask for a context in the runnable's constructor instead? – Vahid Dec 31 '15 at 01:11

1 Answers1

0

How about storing the context in a field in your runnable and passing it as a constructor parameter? This way it could be reusable.

public class MyRunnable implemets Runnable{
    private Context context;

    public MyRunnable(Context context){
        this.context = context;
    }

    public void run(){
        /...
    }
}
Andrea Dusza
  • 2,080
  • 3
  • 18
  • 28