Below is my code in my adapter but when changing fragment the SharedPreferences are not saved and the CheckBoxes in the RecyclerView are all blank when recreating the fragment.
The log is working but something is missing since the state of the checkboxes are not stored or recreated when loading my fragment again.
`public class MyAdapterCharity extends RecyclerView.Adapter {
private String[] mDataset;
MyAdapterCharity(String[] myDataset) {
mDataset = myDataset;
}
private static View v;
private SparseBooleanArray mCheckedItems = new SparseBooleanArray();
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
CheckBox mCheckBox;
TextView mTextView;
CardView mCardView;
RecyclerViewHolder(final View itemView) {
super(itemView);
mCardView = itemView.findViewById(R.id.card_view_charity);
mTextView = itemView.findViewById(R.id.textViewCharity);
mCheckBox = itemView.findViewById(R.id.charityCheckBox);
SharedPreferences update = v.getContext().getSharedPreferences("my_prefs", 0);
String Check = update.getString("CheckBox", "");
Log.e("Checked Array = ", Check);
}
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_item_charity, viewGroup, false);
return new RecyclerViewHolder(v);
}
@Override
public void onBindViewHolder(final RecyclerViewHolder viewHolder, int i) {
//viewHolder.mCheckBox.setChecked(mCheckedItems);
viewHolder.mTextView.setText(mDataset[i]);
viewHolder.mCheckBox.setChecked(mCheckedItems.get(i));
viewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Checked", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Unchecked", Snackbar.LENGTH_SHORT);
snackbar.show();
}
int position = viewHolder.getAdapterPosition();
mCheckedItems.put(position, isChecked);
List<Integer> selected = new ArrayList<>();
for (int i = 0; i < mCheckedItems.size(); i++) {
final boolean checked = mCheckedItems.valueAt(i);
if (checked) {
selected.add(mCheckedItems.keyAt(i));
}
}
Log.e("Checked Array = ", String.valueOf(selected));
SharedPreferences prefs = v.getContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("CheckBox", String.valueOf(selected));
edit.apply();
Log.e("Shared Preference = ", String.valueOf(edit));
}
});
}
@Override
public int getItemCount() {
return mDataset.length;
}
}`
Aucun commentaire:
Enregistrer un commentaire