DialogFragment does not retain checkbox state on scroll

时间:2017-12-18 06:05:34

标签: android checkbox dialogfragment

I have implemented DialogFragmentin my app where I show a list of Countries/States to the user for selection. The list is displayed properly by using the below code. But I just realized when I scroll down the checked boxes and they are not visible on the screen they don't retain check mark when I scroll up again to them. I was thinking I could use an ArrayList to hold the checked items and then use that to check/uncheck the boxes. But I may be there is some other and better way to do it in setMultiChoiceItems. Also, how would I reconcile ArrayList with setMultiChoiceItems parameter isCheckedColumn that is "Show_Ad" in my case.

I don't update the Database until the user presses OK button. So on scroll the Dialog is reusing the old cursor and setting checkboxes according to that. That is what I think is happening.

Can anyone please tell me how I should go about retaining the state of the checkboxes?
Thank you.

 NextDialogIs = "Region";
 regionsCur = database.rawQuery("SELECT distinct max(Show_Ad) as Show_Ad, State_ID as _id, State_Name, State_ID FROM State_Regions group by State_Name ORDER BY State_Name ASC ", null);

 // add a checkbox list

builder.setMultiChoiceItems(regionsCur, "Show_Ad", "State_Name",new DialogInterface.OnMultiChoiceClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which, boolean isChecked){
           // user checked or unchecked a box

            regionsCur.moveToPosition(which);
            if(isChecked) {
               regionID.add(regionsCur.getInt(1));
             }
        }
});

UPDATE

I tried to update Database when the user clicks the checkbox and then tried to refresh the Cursor by running the initial query again like this:

 ContentValues cvs = new ContentValues();

 if(isChecked) {
     cvs.put("Show_Ad", 1);

     Log.d("Updatesss", "Checked");


  } else {
      cvs.put("Show_Ad", 0);

      Log.d("Updatesss", "Unchecked");

  }
  database.update("State_Regions",
                  cvs, "Region_ID = ? ",
                  new String[]{String.valueOf(regionsCur.getInt(3))});

   //re-run the initial query
  regionsCur = database.rawQuery("SELECT distinct max(Show_Ad) as Show_Ad, Region_ID as _id, Region_Name, Region_ID FROM State_Regions group by Region_Name ORDER BY Region_Name ASC ", null);

This is not working either.

0 个答案:

没有答案