0

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.

nck
  • 1,673
  • 16
  • 40
  • Stupid question but : Why are you using an array of boolean ? – compte14031879 Oct 19 '16 at 16:45
  • 1
    Try this. I recommend you to use the method as per the following link and do the delete inside positive button implementation. http://stackoverflow.com/questions/2115758/how-do-i-display-an-alert-dialog-on-android – vidulaJ Oct 19 '16 at 16:45
  • @FrédéricLetellier: I suspect this is done because if using just `final boolean` then onClick would not be able to modify the value, whereas the value within the array can be. – Al Lelopath Oct 19 '16 at 16:47
  • @vidulaJ Agree, I code like this – compte14031879 Oct 19 '16 at 16:52
  • Your method will not wait for your dialog to be dismissed. So do your stuff in onclick listener. – Brijesh Kumar Oct 19 '16 at 17:00
  • @FrédéricLetellier I've updated my message adding why I do that. – nck Oct 19 '16 at 17:06
  • @vidulaJ I've tried doing it like that but it's still the same. I'd like to reuse the code for other things so I'd rather not having to put all my code inside there. – nck Oct 19 '16 at 17:08
  • Your implementation will return false whatever Button the user clicks. As mentioned by @brijesh kumar this method won't wait for the Dialog to be dismissed. Long before Dialog is dismissed the false value has been returned. You got to change this method. – vidulaJ Oct 19 '16 at 17:11
  • @vidulaJ any suggestion how to change this method in order to still be able to use this line "if(!alertMessage())"? – nck Oct 19 '16 at 17:17
  • I won't do it that way though and don't recommend either. But, take a look at this. http://stackoverflow.com/questions/10763986/android-confirmation-dialog-returning-true-or-false – vidulaJ Oct 19 '16 at 17:31

3 Answers3

1

This is because your code doesn't stop running when you show a dialog, so your method will always return false, as it's the default value assigned to it. The best way for you to ask deletion confirmation, is to have the deletion method being called inside of the dialog's positive button.

Let's say you have a listview and you want to delete an item when its clicked. Here's how you should do it.

public class MyActivity extends AppCompatActivity {


    public ListViewCompat listView;
    private List<Object> myObjects;

    public void onCreate(Bundle savedinstance) {
        super.onCreate(savedinstance);
        setContentView(R.layout.activity_my_list);

        listView = (ListViewCompat) findViewById(R.id.my_list_view);
        //Set a listview adapter

        listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                showConfirmationDialog(position);         
            }
        });
    }

    private void showConfirmationDialog(int itemPosition) {
        AlerDialog.Builder builder = new AlerDialog.Builder(this);

        builder.setTitle("Confirmation");
        builder.setMessage("Delete item?")
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            deleteItem(itemPosition);
        });
        builder.setNegativeButton("No", null);

        builder.create().show();
    }

    private void deleteItem(int itemPosition) {
        //Delete item
        myObjects.remove(itemPosition);
    }
}
Jefferson Tavares
  • 983
  • 1
  • 8
  • 23
  • It's the same as in Frederic answer, if I want to reuse the dialog that won't work. – nck Oct 19 '16 at 17:57
  • I don't think it's an issue in this case, as the dialog will be created inside of a method, and there will be no way to call it in another one – Jefferson Tavares Oct 19 '16 at 18:03
0

As you want, the same dialog box for differents actions on differents elements of the same list :

public final static TAG_UPDATE = "update";
public final static TAG_DELETE = "delete";

public void alertMessage(String id, String actionTag) { //the same call for all elements of a list
final String mIdElement = idElement;
final String mActionTag = actionTag;

new AlertDialog.Builder(this)
        .setTitle(R.string.confirmation)
        .setMessage(R.string.sure_confirmation)
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                makeSomething(mIdElement, mActionTag);
            }
        })
        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //no-op
            }
        })
        .setIcon(android.R.drawable.ic_dialog_alert)
        .show();
}

public void makeSomething(String idElement, String actionTag){
    switch(actionTag) {
        case TAG_UPDATE :
            // your update code to update the id element
            break;
        case TAG_DELETE :
            // your delete code to delete the id element
            break;
    } 
}
compte14031879
  • 1,531
  • 14
  • 27
  • This works, but if I want to reuse the confirmation dialog for another purpose I won't be able to do it. – nck Oct 19 '16 at 17:53
  • If you want to delete an element of a list, it's the same dialog for all element. Call the method with parameters (ex : id of element) and pass these parameters to the delete method. If you want use the same dialog for different elements, maybe you are on the bad way.. – compte14031879 Oct 19 '16 at 17:59
  • I mean, if I want to use the same dialog for different actions like "update", "delete" or "add" with for example private boolean showConfirmationDialog(String message). I won't be able to do it in this way. – nck Oct 19 '16 at 18:10
0

Try use interfaces:

public class MainActivity extends AppCompatActivity implements DialogInterface.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate");
        setContentView(R.layout.activity_main);

        new AlertDialog.Builder(this)
                .setTitle("Hello")
                .setMessage("World")
                .setPositiveButton(android.R.string.yes, this)
                .setNegativeButton(android.R.string.no, this)
        .show();

    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch(which) {
            case DialogInterface.BUTTON_POSITIVE:
                Log.d(TAG, "Ok");
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                Log.d(TAG, "Cancel");
                break;
        }

    }
}
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79