How to select a entry in AlertDialog with single choice checkbox android?

LuckyStarr picture LuckyStarr · Apr 14, 2011 · Viewed 87k times · Source

I have an alert dialog with a single-choice list and two buttons: an OK button and a cancel button. The code below show how I implemented it.

private final Dialog createListFile(final String[] fileList) {
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setTitle("Compare with:");

  builder.setSingleChoiceItems(fileList, -1, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      Log.d(TAG,"The wrong button was tapped: " + fileList[whichButton]);
    }
  });

  builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {}
  });

  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {}
  });

  return builder.create();
}

My goal is to obtain the name of the selected radio button when the OK button is tapped. I tried to save the string in a variable, but inside an inner class it is possible to access only final variables. Is there a way to avoid using a final variable to store the selected radio button?

Answer

E-Riz picture E-Riz · Jul 27, 2011

Using a final variable obviously won't work (since it can only be assigned once, at declaration time). So-called "global" variables are usually a code smell (especially when they become part of an Activity class, which is usually where AlertDialogs are created). The cleaner solution is to cast the DialogInterface object to an AlertDialog and then call getListView().getCheckedItemPosition(). Like this:

new AlertDialog.Builder(this)
        .setSingleChoiceItems(items, 0, null)
        .setPositiveButton(R.string.ok_button_label, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
                int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
                // Do something useful withe the position of the selected radio button
            }
        })
        .show();