0
votes

Hi I am trying to call a function from menu item. But I am getting this exception. android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

Here is my code..

public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menu1, menu);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch(item.getItemId())
        {
        case R.id.write :
            writeToTag();
            return true;

        case R.id.exit :
            exitApplication();
            return true;

        default :
            return super.onMenuItemSelected(featureId, item);
        }

    }

    private void exitApplication() {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getApplicationContext());
        alertDialog.setMessage("Do You Want To Exit..?")
        .setPositiveButton("Yes",new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                NFCTagWriterActivity.this.finish();
            }
        }).setNegativeButton("No",new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                onStart();

            }
        }).show();

        AlertDialog alert = alertDialog.create();
    }
1

1 Answers

2
votes

You cannot create a AlertDialog using an application context. You need to use an Activity Context. In your case this would be appropriate.