Search code examples
androidsharedpreferencesandroid-sharedpreferences

Using SharedPreferences in a runnable


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.


Solution

  • 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(){
            /...
        }
    }