Emilla
Emilla

Reputation: 494

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

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);
    }

Upvotes: 3

Views: 2867

Answers (2)

Stefano Ortisi
Stefano Ortisi

Reputation: 5326

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();

Upvotes: 5

karllindmark
karllindmark

Reputation: 6071

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);

Upvotes: 1

Related Questions