I have a method to delete something from a database. I want to get the user confirmation. In order to do it I implement a boolean function to get the confirmation with a dialog.
Well my problem is that doesn't matter whether I choose yes or no I always get the same false result.
(I used final boolean[]beacuse otherwise I get an error)
This is the method:
public boolean alertMessage() { //Confirmation to delete routine
final boolean[] confirmation = {false};
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
confirmation[0] =true;
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
// do nothing
confirmation[0]=false;
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.sure_delete)
.setPositiveButton(R.string.yes, dialogClickListener)
.setNegativeButton(R.string.no, dialogClickListener).show();
return confirmation[0];
}
And this is how I check it in my delete code:
//CONFIRMATION
if(!alertMessage()){
return;
}
Update: Try this with one answer suggestion but still the same:
public boolean alertMessage() { //Confirmation to delete routine
final boolean[] confirmation = {false};
new AlertDialog.Builder(this)
.setTitle(R.string.delete)
.setMessage(R.string.sure_delete)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
confirmation[0]=true;
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
confirmation[0]=false;
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return confirmation[0];
}
I put final boolean [] becuase with just a boolean I get an error:
"Variable is accessed from within an inner class, needs to be declared final."
And once I declare it final:
"Can not assign a value to final variable"
So I have to transform it into an array. I would like it to be a boolean method and don't implement the delete inside the "yes", because I want to reuse it in other methods.