I am currently using SharedPreferences key, value pairs to save the state, but can't seem to read from the prefs file and check the boxes.
I have written this self-explanatory code. However, a NullPointerException is thrown in the line list.findViewHolderForAdapterPosition(i).itemView.performClick();
. I just want to know how to set the checkboxes in Recyclerview list to checked and save that state. Please help.
btnGetSelected.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuilder stringBuilder = new StringBuilder();
for (Number number : numbers) {
if (number.isSelected()) {
if (stringBuilder.length() > 0)
stringBuilder.append(", ");
stringBuilder.append(number.getTextONEs());
Log.e("Checked", "here");
setPreference(getApplicationContext(), "1", number.getONEs());
} else {
Log.e("Not checked", "here");
setPreference(getApplicationContext(), "0", number.getONEs());
}
}
}
});
try {
for (int i = 0; i < tocArray.length; i++) {
String value = getPreference(getApplicationContext(),Integer.toString(i));
if (value.equalsIgnoreCase("1")) {
list.findViewHolderForAdapterPosition(i).itemView.performClick();
} else {
//Do Nothing
}
}
} catch (Exception e) {
e.printStackTrace();
}
This is from the holder of the Recyclerview;
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.bindData(numbers.get(position));
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(numbers.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
numbers.get(holder.getAdapterPosition()).setSelected(isChecked);
}
});
Can you also please explain this whole concept of recyclerview and cards and why the "holder" is needed? Thanks. Please help! Regards
Try add these methods to your Activity:
Change onResume() of Activity:
When you need to save, just call saveSelectedPositions(). Hope this help!