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

前端 未结 28 1790
死守一世寂寞
死守一世寂寞 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 09:13

    Your dialog should not be a "long-lived object that needs a context". The documentation is confusing. Basically if you do something like:

    static Dialog sDialog;
    

    (note the static)

    Then in an activity somewhere you did

     sDialog = new Dialog(this);
    

    You would likely be leaking the original activity during a rotation or similar that would destroy the activity. (Unless you clean up in onDestroy, but in that case you probably wouldn't make the Dialog object static)

    For some data structures it would make sense to make them static and based off the application's context, but generally not for UI related things, like dialogs. So something like this:

    Dialog mDialog;
    
    ...
    
    mDialog = new Dialog(this);
    

    Is fine and shouldn't leak the activity as mDialog would be freed with the activity since it's not static.

提交回复
热议问题