简体   繁体   中英

Show sharedpreference inside RecyclerView Adapter

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)

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

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

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

This is what I did. (If you cant access class "context" inside SharedPreferences)

  1. Create a context of the adapter class by " Context mConext "; or "p rivate WeakReference mContext; "
  2. Instead giving " mContext " use " this.mContext.get() " wherever you need to use context inside the SharedPrefernce. like SharedPreferences preferences = this.mContext.get().getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE);

I tried so many other solutions, but couldn't find the thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM