mardi 12 octobre 2021

check the selected checkbox in android

There is a dynamic set of checboxes and I want to save the clicked checkbox state. I have been able to have a correct position of checkbox in the db but I can not use it to check the right checkbox. Every time I select a checkbox, when I reopen that, it is unchecked. Here is the implementation

int checkbox_id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
      
           //

     setTrackItem();

}

 
private void setTrackItem() {

    if (trackSelector != null) {
      
            int trackType = mappedTrackInfo.getRendererType(rvalue);
            TrackGroupArray trackGroupArray = mappedTrackInfo.getTrackGroups(rvalue);
            if (trackType == C.TRACK_TYPE_TEXT) {
                 int checkbox_pos = db.readPos(checkbox_id));
                        if (checkbox_pos == 0) {
                            index = 0;
                        } else if (checkbox_pos == 1) {
                            index = 1;
                        } else if (checkbox_pos == 2) {
                            index = 2;
                        }
                builder.setSelectionOverride(rvalue, mappedTrackInfo.getTrackGroups(rvalue), override);
            }
        }

        trackSelector.setParameters(builder);
    }
}

 for (int check_pos= 0; index < array.get(check_pos).length; check_pos++) {
                                    
     checkBox = new CheckBox(this);
     checkBox.setId(check_pos);
     checkBox.setText("cb");
     layout.addView(checkBox);
     checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
         @Override
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
               checkbox_id = buttonView.getId();
               boolean success = db.updPos(checkbox_id);
             if (success){
               setTrackItem();

          //     checkBox = checkBox.findViewById(checkbox_pos);
          //     checkBox.setChecked(true);
            }
       });
                                      
 }

When I start the activity again, the checkbox_pos returns the correct position and setTrackItem in onCreate() works fine as well meaning that if I had selected second checkbox, checkbox_pos return 1 and index is 1 which are correct, but the only problem is that selected checkbox does not stay checked. I have tried something above its giving null pointer exception and nothing has worked so far.




Aucun commentaire:

Enregistrer un commentaire