Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Alert Dialog inside of Handler

I want to create an alert dialog from a handler which gets signaled when a thread terminates this is my code which causes:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

Handler handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {

        if (dialog != null)
        {
            dialog.dismiss();
            dialog = null;
        }

        switch (serverResponseCode)
        {
        case 200:
        {
            AlertDialog alertDialog;
            alertDialog = new AlertDialog.Builder(getApplicationContext()).create();
            alertDialog.setTitle("Super :)");
            alertDialog.setMessage("Poza a fost trimisa cu success.");
            alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {

                  public void onClick(DialogInterface dialog, int id) {

                     finish();

                } }); 
            alertDialog.show();
            serverResponseCode = -1;

            break;
        }
        default:
        {
            AlertDialog alertDialog;
            alertDialog = new AlertDialog.Builder(getApplicationContext()).create();
            alertDialog.setTitle("Eroare :(");
            alertDialog.setMessage("Eroare la trimiterea pozei.");
            alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {

                  public void onClick(DialogInterface dialog, int id) {

                     finish();

                } }); 
            alertDialog.show();

            break;
        }
        }


         }
     };
like image 871
opc0de Avatar asked Jan 19 '26 21:01

opc0de


1 Answers

The problem probably is getApplicationContext() isn`t yout activity context.

    alertDialog = new AlertDialog.Builder(getApplicationContext()).create();
    //should be change to
    alertDialog = new AlertDialog.Builder( YourActivity.this ).create();
like image 96
markwu Avatar answered Jan 21 '26 11:01

markwu