Home > Mobile >  Android AlertDialog not showing up
Android AlertDialog not showing up

Time:11-03

I'm trying to open an alert dialog within a function. The code just stops running when calling the .show() at the end of my code. When I'm trying to execute the exact same code snippet in the onCreate function of the same class, everything works fine. Why won't the Dialog open, when I'm trying to open it from another function?

    DialogInterface.OnClickListener dialogClickListener = (dialog, which) -> {
        switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                //Yes button clicked
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                //No button clicked
                break;
        }
    };


    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();

CodePudding user response:

Try like this:

         AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener);
    AlertDialog alert=builder.create();
    alert.show();

CodePudding user response:

You can try this, it should be easy:

  AlertDialog alertDialog = new AlertDialog.Builder(
                YourDialogActivity.this).create();

   alertDialog.setTitle("Alert Title");
   alertDialog.setMessage("Alert Message");

   alertDialog.setPositiveButton("YES",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(),
                    "YES clicked", Toast.LENGTH_SHORT)
                    .show();
        }
    });

   alertDialog.setNegativeButton("NO",
     new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(),
                    "NO clicked", Toast.LENGTH_SHORT)
                    .show();
            dialog.cancel();
        }
    });

   alertDialog.show();

Please, set how you use that function where it doesn't work for you

  • Related