Bence
Bence

Reputation: 109

How to acces SharedPrefences from recyclerView adapter?

I want to acces SharedPrefences from my adapter because I want to check a variable to set an ImageView visible or gone.

class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener{


ArrayList<String> mData;
public ImageView mMinus;
public static final String SHARED_PREFS_DATA = "sharedPrefsData";



public MainAdapter(ArrayList<String> data) {
        mData = data;
}



@NonNull
@Override
public MainAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MainAdapter.ViewHolder holder, int position) {
    holder.mText.setText(mData.get(position));

    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS_DATA, 0);
    int a = sharedPreferences.getInt("visible", 0);
    if(a == 0)
       holder.mMinus.setVisibility(View.GONE);
    else
       holder.mMinus.setVisibility(View.VISIBLE); 

}

error: cannot find symbol method getSharedPreferences(String,int)

Upvotes: 0

Views: 61

Answers (1)

Muhammad Usman
Muhammad Usman

Reputation: 1258

1.Pass the context from the Activity to the adapter and using this context you can access the shared preferences

2.You can also pass the Activity reference instead of Context

Upvotes: 3

Related Questions