Collect value from an AlertDialog

1

I'm creating a Alertdialog but the value it returns is always 0. I have defined a variable in the Activity and I assign it the value but it does not work for me. Thanks for your answers.

private int result;

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCustomTitle(myMsg)
            .setItems(array, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result = which;
                    Log.d("DIALOG", result);
                }
            });

    AlertDialog dialog = builder.create();
    dialog.show();

    Log.d("METODO", ""+result);

The log inside the dialog "DIALOG" effectively returns the correct value but the result variable in the "METHOD" log is always equal to zero and I do not know how to pick up the value returned by the dialog. I have read in the documentation that it is not possible to apply a wait, as does the JOptionPane in Java, which could solve my problem.

    
asked by M.J.D 21.04.2018 в 21:42
source

1 answer

1

The explanation is that when this part of the code is performed, the AlertDialog is created, but the value of the variable result is not modified at that moment, therefore only the same value is printed:

Log.d("METODO", ""+result);

The variable result will only change when clicking on the AlertDialog , since the onClick() method is only called when executing this action.

public void onClick(DialogInterface dialog, int which) {
                    result = which;
                    Log.d("DIALOG", result);
                }
    
answered by 22.04.2018 / 00:48
source