Reputation: 2179
final String[] choices = { "Item 1", "Item 2", "Item 3"};
final AlertDialog dialog= new AlertDialog.Builder(
TestSubjectCalendar.this)
.setTitle("Title")
.setSingleChoiceItems(choices, pos, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //gives error
// MORE CODE
}
}).create();
dialog.show();
dialog.dismiss()
is giving the following errors:
The local variable dialog may not have been initialized
What I want is that when I click an item from the choice list in the dialog
, the dialog
should disappear. So how can I go about doing that?
PS: I know I can use setItems()
instead of setSingleChoiceItems()
, but I want to use the latter as it provides radio buttons.
Upvotes: 1
Views: 2578
Reputation: 15476
Basically since you reference dialog in the same code block that dialog is initialized, Eclipse/Java
compiler is concerned that the dialog reference used in onClick(DialogInterface dialog, int which)
may be invalid.
So changing it to:
final AlertDialog dialog= new AlertDialog.Builder(
TestSubjectCalendar.this).create();
dialog.setTitle("Title");
dialog.setSingleChoiceItems(choices, pos, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //gives error
// MORE CODE
}
});
dialog.show();
should do the trick. On a side note, I don't actually get any error with your code, may have to do with compiler setting.
Upvotes: 0
Reputation: 4349
You need to change name of the dialog because there is same name use for AlertDialog and DialogInterface in onClick()...
Try following changes and checked it out.
@Override
public void onClick(DialogInterface dialog1, int which) {
dialog1.dismiss(); //gives error
// MORE CODE
}
That is resolve the name override, I just change dialog to dialog1 in onClick().
Upvotes: 1
Reputation: 12181
Try this:
final String[] choices = { "Item 1", "Item 2", "Item 3"};
final AlertDialog.Builder dialog= new AlertDialog.Builder(TestSubjectCalendar.this);
dialog.setTitle("Title")
.setSingleChoiceItems(choices, pos, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //gives error
// MORE CODE
}
}).create();
dialog.show();
Upvotes: 0