How to use data stored in sharedpreferences from non-activity class

岁酱吖の 提交于 2019-12-13 14:30:51

问题


I am trying to get and update the data which I stored in sharedpreferences xml file from a non-activity class.But I dont know how to reach the data stored in sharedPreferences from a non-activity class in android.In my activiy class i can store data in sharedprefences and i also can retrive these data in my activiy class. However i can not retrive these data from a non-activiy class. My code is below.Thank you...

    mSharedPrefs = getSharedPreferences("storageforfavorite", 0);
    mPrefsEditor = mSharedPrefs.edit();

    for(int i= 0;i<names.size();i++){
        mPrefsEditor.putString(indexForFav[i],"0"); 
    }
    mPrefsEditor.commit();

    for(int i=0;i<names.size();i++){
        String keyForFav=mSharedPrefs.getString(indexForFav[i], "2");
        valueForFav.add(keyForFav);
    }

回答1:


The key is have access to the Context object. So if you want to use sharedPreferences inside an object, maybe you should pass a Context object in the class constructor. Doing this way you can do this:

SharedPreferences prefs = context.getSharedPreferences();



回答2:


You'll have to pass a Context to be able to access SharedPreferences from a non-Activity class.

Example:

// mContext => Context-object passed from calling Activity
SharedPreferences mSharedPrefs = mContext.getSharedPreferences("storageforfavorite", 0);


来源:https://stackoverflow.com/questions/11409759/how-to-use-data-stored-in-sharedpreferences-from-non-activity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!