How do I use sharedPreferences outside of an Activity?

前端 未结 3 1920
一向
一向 2020-12-17 16:32

I\'ve been stuck on this very simple problem for hours now and Ive been unable to find any suitable solutions through google.

I am trying to use the SharedPreference

相关标签:
3条回答
  • 2020-12-17 16:39

    Where do you instantiate your Model class?

    Just pass either a context or the SharedPreferences to the constructor:

    public class Model {
        private final Context context;
        private final SharedPreferences sharedPrefs;
    
        public Model(Context context) {
            this.context = context;
            sharedPrefs = context.getSharedPreferences("name", 0);
        }
    
        private String doSomething(){
            return sharedPrefs.getString("key", "defValue");
        }
    }
    
    0 讨论(0)
  • 2020-12-17 16:42

    You can use SharedPrederences from any code that holds a Context. From the Activity documentation at http://developer.android.com/reference/android/app/Activity.html:

    Activity persistent state is managed with the method getPreferences(int), allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying Context.getSharedPreferences() method to retrieve a preferences object stored under a specific name. (Note that it is not possible to share settings data across application packages -- for that you will need a content provider.)

    0 讨论(0)
  • 2020-12-17 16:44

    SharedPreferences isn't called only from Activity, but from Context (which Activity extends) so you can use the application context as well.

    0 讨论(0)
提交回复
热议问题