How do I use sharedPreferences outside of an Activity?

前端 未结 3 2037
一向
一向 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条回答
  •  旧时难觅i
    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");
        }
    }
    

提交回复
热议问题