简体   繁体   中英

Alert dialog is not displaying

Hi all I am creating an alert dialog in android by clicking a button. I used onClick property of XML and calling function. My code is

public void selectPhoneType(View view)
{
    String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"};
    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setTitle("Select Label");
    AlertDialog alert = builder.create();
    alert.show();}

but this code is not showing alert and giving error like

BadTokenException: Unable to add window -- token null is not for an application. 

Please tell me what is wrong with this code.

new AlertDialog.Builder(getApplicationContext());

I think this is the problem. Have you tried:

new AlertDialog.Builder(YourActivityClassName.this);

Passing requireActivity() instead of requireContext() worked for me..!! I think it requires activity context!!.

If you are calling dialog code in background thread then it won't work. You should call UI related code in main thread, if you are not doing it then it will not show you the dialog.

  1. If you want show the dialog in the background task then use handler instead.

    new Handler().post(new Runnable(){ showDialog(); })

  2. Make sure create() and show() method is called.

  3. Never forgot 1st and 2nd point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM