Sarthak Sharma
Sarthak Sharma

Reputation: 137

android - How to use Shared Preferences between two different RecyclerViewAdapters

I have two RecyclerView Adapters. And, I am using SharedPreferences in these two adapters.

In the first adapter, I am saving the String value of araayList size like String.valueOf(dataList.size()). The code in the first adapter for shared prefernces is like this:

public class ItemRowHolder extends RecyclerView.ViewHolder {

    protected TextView itemTitle;
    protected RecyclerView recycler_view_list;
    protected TextView lblnoOfItems;

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

        this.itemTitle = (TextView) view.findViewById(R.id.itemTitle);
        this.recycler_view_list = (RecyclerView) view.findViewById(R.id.recycler_view_list);
        this.lblnoOfItems = (TextView) view.findViewById(R.id.lblnoOfItems);

        sharedPreferences = mContext.getSharedPreferences("DataList", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString("MyDataList", String.valueOf(dataList.size()));
        editor.apply();
    }
}

And, I am getting the shared Preference value in another adapter inside onCreateViewHolder(). Here is the code:

@Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(viewGroup.getContext());
    String value = pref.getString("MyDataList", null);

    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
    SingleItemRowHolder mh = new SingleItemRowHolder(v);
    return mh;
}

I debugged it several times and found that I am getting null when I am receiving in the second adapter here, String value = pref.getString("MyDataList", null).

Am I doing something wrong here? Also, can someone please tell if this is the right method for receiving shared preference values in RecyclerView Adapter.

Upvotes: 1

Views: 526

Answers (1)

Pulkit
Pulkit

Reputation: 1040

In 2nd Adapter in onCreateViewHolder(), your shared pref is wrong, Replace

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(viewGroup.getContext());

with

SharedPreferences pref = viewGroup.getContext().getSharedPreferences("DataList", Context.MODE_PRIVATE);

You can learn more about this by reading the following android documentation: https://developer.android.com/training/basics/data-storage/shared-preferences.html#GetSharedPreferences

Upvotes: 1

Related Questions