jeetdeveloper
jeetdeveloper

Reputation: 191

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

Upvotes: 0

Views: 807

Answers (3)

MONK
MONK

Reputation: 189

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

Upvotes: 1

rafsanahmad007
rafsanahmad007

Reputation: 23881

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.

Upvotes: 1

Poorya Taghizade
Poorya Taghizade

Reputation: 56

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

Upvotes: 0

Related Questions