lundi 1 novembre 2021

how to save the checkbox state in sqlite android

I have a dialog containing a dynamic set of checkboxes. I have set up the db, the only problem is that whenever I select a checkbox, it works fine but it does not stay checked. When I open the dialog, that checkbox is not checked anymore.

    case R.id.dialog:

       dialog = new Dialog(this);
       dialog.setContentView(R.layout.dialog);

       dialog.show();
                
       for (int IndexNo = 0; IndexNo <  tgroup.get(groupIndex).length; IndexNo++){ 
                        
           checkBox1 = new CheckBox(this);
           checkBox1.setId(IndexNo);
           checkBox1.setText(IndexNo);
                        
           checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                 @Override
                 public void onCheckedChanged(CompoundButton buttonView, boolean 
                               isChecked) {
                   if (isChecked) {
                       checkbox_position = buttonView.getId();
                       boolean success = db.updateCheckboxPosition(
                                            getId(),
                                            String.valueOf(checkbox_position), 1);
                                    
                       if (success) {
                          setItem();
                       }
                  }  else {
                       boolean success = db.updateCheckboxPosition(getId(),
                               String.valueOf(checkbox_position), 0);
                  }
                            
              });                
          }

 }

this is the update in db

public boolean updateCheckboxPosition(String _id,String checkbox_pos, int isChecked){
    SQLiteDatabase database = this.getWritableDatabase();
    String selection = "_id = ?";
    ContentValues contentValues = new ContentValues();

    contentValues.put(_ID,_id);
    contentValues.put(CHECKBOX_POS,checkbox_pos);
    contentValues.put(CHECKBOX_STATUS,isChecked);

    long result = database.update(TABLE_NAME , contentValues , _ID + " =? " ,
            new String[]{_id});
    if (result == -1){
        return false;
    } else {
        return true;
    }

}

By default, there is no checkbox selected. The above works fine but does not keep the selected box checked. When you select a checkbox, it checks the clicked one and last checkbox. When you open the dialog after no checkbox is checked.




Aucun commentaire:

Enregistrer un commentaire