Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

前端 未结 28 1410
死守一世寂寞
死守一世寂寞 2020-11-22 08:42

My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:

AlertDialog.Builder builder = new Al         


        
28条回答
  •  一生所求
    2020-11-22 09:10

    If you are outside of the Activity then you need to use in your function "NameOfMyActivity.this" as Activity activity, example:

    public static void showDialog(Activity activity) {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setMessage("Your Message")
            .setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();
    }
    
    
    //Outside your Activity
    showDialog(NameOfMyActivity.this);
    

提交回复
热议问题