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

前端 未结 28 1288
死守一世寂寞
死守一世寂寞 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 08:56

    Guys I got a simple cheat sheet. create a file give it any name then in it write this code

    fun Context.alertdialog(context: Context, msg: String, icon: Drawable, title:String){
        val alertDialog = AlertDialog.Builder(context)
        alertDialog.setIcon(icon)
            .setTitle(title)
            .setMessage(msg)
        alertDialog.show()
    }
    

    now when you need to show an alert dialog only use this method anywhere

    requireActivity().alertdialog(requireContext(), resources.getString(R.string.pass_title),
                    resources.getDrawable(R.drawable.pass_ic_name), "title")
    

    Goodluck for Kotlin

    0 讨论(0)
  • 2020-11-22 08:57

    Or another possibility is to create Dialog as follow:

    final Dialog dialog = new Dialog(new ContextThemeWrapper(
                this, R.style.MyThemeDialog));
    
    0 讨论(0)
  • 2020-11-22 08:58

    In my case work:

    this.getContext();
    
    0 讨论(0)
  • 2020-11-22 09:00

    If you are using a fragment and using AlertDialog/Toast message then use getActivity() in the context parameter.

    like this

    ProgressDialog pdialog;
    pdialog = new ProgressDialog(getActivity());
    pdialog.setCancelable(true);
    pdialog.setMessage("Loading ....");
    pdialog.show();
    
    0 讨论(0)
  • 2020-11-22 09:00

    I think it may happen as well if you are trying to show a dialog from a thread which is not the main UI thread.

    Use runOnUiThread() in that case.

    0 讨论(0)
  • 2020-11-22 09:00

    Here is how I resolved same error for my application:
    Adding the following line after creating the dialog:

    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);  
    

    You will not need to acquire a context. This is particularly useful if you are popping up another dialog over current popped up dialog. Or when it's not convenient to get a context.

    Hope this can help you with your app development.

    David

    0 讨论(0)
提交回复
热议问题