Ad

Fetching Shared Preferences String Value In Recyclerview Adapter

I want to fetch String value from shared preferences and show it in Recylerview Adapter. Any help will be appreciated
This is my code

public  class MyViewHolder extends RecyclerView.ViewHolder {

   // private SharedPreferences prefs;

public Context context;

public ABCAdapter(List<ChatHistory>MessagesList,Context context) {

    this.MessageList = MessagesList;
    context=this.context;


}

    public MyViewHolder(View view) {
        super(view);


       // SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        //String profile_name = pref.getString("profile_name", null);

       prefs = context.getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
        String ipAdrs=prefs.getString("profile_name", "");
 }
}

profile_name is already stored in shared preferences.

here I am getting this error.

Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null

Ad

Answer

Here:

public ABCAdapter(List<ChatHistory>MessagesList,Context context) {

    this.MessageList = MessagesList;
    context=this.context;
}

should be:

public ABCAdapter(List<ChatHistory>MessagesList,Context context) {

    this.MessageList = MessagesList;
    this.context=context;   //this refers to class variable
}

Make sure to pass the activity context while creating the adapter.

Ad
source: stackoverflow.com
Ad