0

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

jeetdeveloper
  • 191
  • 1
  • 13

3 Answers3

1

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.

rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
1

A much more easier(and better way) would be

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

Also passing the Context to ViewHolder it is a very bad practice. You can get the Context whenever you need from any View

MONK
  • 179
  • 2
  • 15
0

you should pass SharedPreferences object to adapter Constructor and read data from it