Reputation: 226
I have problem to pass context from Activity to Adapter.
I am calling my sharedpreference like this:
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
And this one need context, so i am using : getApplicationContext()
But this not work in the Adapter (RecyclerView), is there someone facing the same issue ?
Adding the adapter into the Manifest file will solve the problem ? (Just a suggestion)
Upvotes: 3
Views: 4813
Reputation: 103
I suggest you to separate your preference-managing code into singleton class so you can get access to the preferences anywhere, just like this
public class SharedPreferenceManager {
private static final SharedPreferenceManager ourInstance = new SharedPreferenceManager();
public static SharedPreferenceManager getInstance() {
return ourInstance;
}
private SharedPreferenceManager() {
}
private SharedPreferences preferences;
public void init(Context ctx) {
preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
}
public String getValueByKey(String key) {
return preferences.getString(key, "");
}..other functions....}
you should call the SharedPreferenceManager.getInstance().init(this)
in your onCreate() in the activity
and after you can get access to SP wherever you want: SharedPreferenceManager.getInstance().getValueByKey("somekey")
Upvotes: 0
Reputation: 2151
I am not sure what you are asking but here is a solution that I can think of. Pass the context of the calling activity in your adapter through constructor and then use that context.
Context ctx;
public YourAdapter(Context ctx){
this.ctx = ctx;
}
now in your adapter you can do this
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
Upvotes: 2
Reputation: 3665
In your adapter create constructor with Context
like this,
public AdapterList(Context ctx){
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
}
and create it by passing
adapter = new YourAdapter(getApplicationContext());
Upvotes: 0