问题
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