Reputation: 10012
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String choice="";
AlertDialog.Builder builder1 = new AlertDialog.Builder(parent.getContext());
builder1.setMessage("Do you want to accept this vendor's quote?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
choice= "true" //cant access non final variable
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
if(choice.equals("true"){
// do something
}
}
How can i access 'choice' variable without making it final or is there any other way to get to know if user has pressed either on positive button or negative button
Upvotes: 0
Views: 1721
Reputation: 495
The clean way is to make the onClick
method call a "setter" method in your parent class.
public class Activity {
private boolean choice = false;
...
//In your method
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
setChoice(true);
}
});
}
...
public void setChoice(boolean choice) {
this.choice = choice;
}
}
Upvotes: 2
Reputation: 607
Declare the variable right outside, just inside the class definition.
Upvotes: 0
Reputation: 7709
Declare your variable as a field in the class:
public class YourClass {
private String choice;
...
}
Upvotes: 3
Reputation: 288
The variable has to be final, e.g. Eclipse says:
Cannot refer to a non-final variable choice inside an inner class defined in a different method
Upvotes: 0