Fragment 使用 Dialog 报错Unable to add window -- token null is not for an application

In the context of the fragment which get accustomed to using getActivity (). GetApplicationContext ()

error code:

private void showChoiceUpdata(){
    new AlertDialog.Builder(getActivity().getApplicationContext())
            .setTitle ( " detected a new version " )
            .setMessage ( " you want to upgrade it ." )
            .setPositiveButton("", null)
            .setNegativeButton("", null)
            .show();
}

报错Unable to add window -- token null is not for an application

Correct codes:

private void showChoiceUpdata(){
    new AlertDialog.Builder(this.getActivity())
            .setTitle ( " detected a new version " )
            .setMessage ( " you want to upgrade it ." )
            .setPositiveButton("", null)
            .setNegativeButton("", null)
            .show();
}

For AlertDialog, it is the need to rely on a View, the View is corresponding to the Activity. Only one Activity can add a form.

getApplicationContext () refers to the entire application context.

For an application for Context. Its life cycle is the entire application life cycle. For the Activity for. When it destroy its life cycle is over.

AlertDialog belongs Acitivity, and when it Activity destruction must be destroyed, so here we are specified Activity in Context.

By the way in the use of Dialog Activity, ginseng is still not used Context, with this or MyActivity.this

Site  https://www.cnblogs.com/mthoutai/p/6953542.html



Published 37 original articles · won praise 10 · views 60000 +

Guess you like

Origin blog.csdn.net/shsh_0415/article/details/79892112