-->

NPE when invoking getDialog.getWindow in DialogFra

2019-07-18 19:25发布

问题:

in my DialogFragment, I just do:

    override fun onResume() {
        super.onResume()
        dismissDialog()
        getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dpToPx(220f, resources));
        getDialog().getWindow().setGravity(Gravity.BOTTOM)
        getDialog().setCanceledOnTouchOutside(false)
    }

but I got NPE:

Unable to resume activity {PublishActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window android.app.Dialog.getWindow()' on a null object reference
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3308)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3344)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1583)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5773)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:799)

In my activity, I start a DialogFragment and got this error. It happens several times.

回答1:

you should check against getDialog() if its not null, you should copy your code to onViewCreated/onCreate to apply the LayoutParameters and you can keep your code in Resume as long as you check against NPE

    if(getDialog() !=null){
        dismissDialog()
        getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dpToPx(220f, resources));
        getDialog().getWindow().setGravity(Gravity.BOTTOM)
        getDialog().setCanceledOnTouchOutside(false)
    }