How to get selected item of a singlechoice Alert Dialog?

I know this is an old post, but i just came across it, and found that this solution seems at bit more simple that whats been posted here.

You can just do like this:

In your onClick() handler on the dialog positive button, add the following code:

ListView lw = ((AlertDialog)dialog).getListView();
Object checkedItem = lw.getAdapter().getItem(lw.getCheckedItemPosition());

Note that if you haven't selected any option it will crash you have to add a check here before getting the checkedItem with if(lw.getCheckedItemCount() > 0)


I tried to use ListView.setSelection(int) but it never worked as expected so instead I decided to make use of View.setTag() to temporarily store the selected position.

.setSingleChoiceItems(adapter, -1,
        new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            ListView lv = ((AlertDialog)dialog).getListView();
            lv.setTag(new Integer(which));
        }
})

The tag can then be accessed easily after a button click.

.setPositiveButton(R.string.button_text,
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        ListView lv = ((AlertDialog)dialog).getListView();
        Integer selected = (Integer)lv.getTag();
        if(selected != null) {
            // do something interesting
        }
    }
})