My question is similar to this and this. But I cannot apply the solutions in those questions to my case.
My case is as follows: I have GridView consists of just CheckBoxes. I set setOnCheckedChangeListener in my Adapter's getView method, so that as soon as the status of CheckBox is changed, current status of the CheckBox is registered to SharedPreferences. And in getView also, I'm reading the current status of the CheckBox and set its status as so. Yet scrolling down and back up makes the checked boxes unchecked.
How can I solve this problem? Here is my custom adapter:
public class KnowledgeItemAdapter extends ArrayAdapter<KnowledgeItem> {
private String currentKey;
public KnowledgeItemAdapter(Activity context, ArrayList<KnowledgeItem> knowledgeItems){
super(context, 0, knowledgeItems);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View knowledgeItemView = convertView;
if (knowledgeItemView == null){
knowledgeItemView = LayoutInflater.from(getContext()).inflate(R.layout.item_knowledge, parent, false);
}
knowledgeItemView.setClickable(true);
knowledgeItemView.setFocusable(true);
knowledgeItemView.setBackgroundResource(android.R.drawable.menuitem_background);
final KnowledgeItem currentKnowledgeItem = getItem(position);
final CheckBox knowledgeCheckBox = (CheckBox) knowledgeItemView.findViewById(R.id.item_knowledge_check_box);
final SharedPreferences prefs = getContext().getSharedPreferences("com.example.myapplication", Context.MODE_PRIVATE);
currentKey = currentKnowledgeItem.getPrefsKey();
Boolean status = prefs.getBoolean(currentKey, false);
knowledgeCheckBox.setText(currentKnowledgeItem.getText());
knowledgeCheckBox.setChecked(status);
knowledgeCheckBox.setOnCheckedChangeListener( //this);
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
prefs.edit().putBoolean(currentKnowledgeItem.getPrefsKey(), isChecked).apply();
}
}
);
return knowledgeItemView;
}
}