Reputation: 2594
I am using AlertDialog
in my program, whenever i do tap on any of the item in Dialog, always getting:
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
Here is my implementation :
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("which::--", String.valueOf(which));
});
Upvotes: 0
Views: 2573
Reputation: 2594
Here is the simple solution to get index or position
of tapped item:
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
Upvotes: 1
Reputation: 546
According to the documentation, the "which" parameter indicates "The button that was clicked (e.g. BUTTON1) or the position of the item clicked."
Here you put your listener (DialogInterface.OnClickListener()) on your PositiveButton so "which" will always return BUTTON1 or BUTTON_POSITIVE (see here http://developer.android.com/reference/android/content/DialogInterface.html).
You must put your listener on your list using the function
setSingleChoiceItems (CharSequence[] items, int checkedItem, DialogInterface.OnClickListener listener)
for example or setMultiChoiceItems (CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)
if you want to allow multi-items selection.
Upvotes: 0