Dynamix Dynamix - 2 months ago 21
Android Question

Check a CheckBox within a RecyclerView when it is loaded

I am creating a

RecyclerView
which has items. Each item has a
CheckBox
,
ImageButton
and a
TextView
as stated below:

public class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
RelativeLayout item;
TextView id;
TextView name;
ImageButton delete;
CheckBox checkBox;

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

item = (RelativeLayout) view.findViewById(R.id.layout_item_item);
id = (TextView) view.findViewById(R.id.layout_item_id);
name = (TextView) view.findViewById(R.id.layout_item_name);
delete = (ImageButton) view.findViewById(R.id.layout_item_delete);
checkBox = (CheckBox) view.findViewById(R.id.layout_item_checkbox);
}
}


I want the
checkbox
view to be checked only if a certain value in a column of a database is equal to
1
. If the value is
0
, it should not be checked. I have started off with the code below:

SQLiteDatabaseAdapter database = new SQLiteDatabaseAdapter(context);
database.open();

Cursor cursor = database.getAllItems(table);

if (cursor.moveToFirst()) {
do {
if (cursor.getInt(2) == 0) {
viewHolder.checkBox.setChecked(false);
}

else {
viewHolder.checkBox.setChecked(true);
}

} while (cursor.moveToNext());

}

database.close();


This code works but it checks the first row in the database and if the
checked
column is
1
, it changes every single
CheckBox
to be checked. I only want the
CheckBox
associated with one particular row to be checked, not every single one. How do I exactly do that?

Answer

I recommend that you create a HashMap<> and link the IDs and the checked states. Then, you can reference from the HashMap<> and get the checked states.

HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();

Then, in your onBindViewHolder function, you can use the following to check you CheckBox:

if (hashMap.get(position) == 0) {
    // not checked
}

else {
    // checked
}

Make sure you add the IDs and checked states from your SQLite database.