android使用AlertDialog提示 Unable to add window -- token null is not for an application的解决方案

来源:互联网 发布:微社区2.0源码下载 编辑:程序博客网 时间:2024/06/07 12:37

           第一次使用AlertDialog,当然首先得查阅android开发文档,见http://developer.android.com/reference/android/app/AlertDialog.html

            基本的使用方法就不在这赘述了,在使用过程中出现一个问题,就是在AlertDialog.Builder(Context context)的时候,这个context我是直接使用的getApplicationContext()来获取的,虽然编译没有错误,但是在运行的时候,程序会报错,logcat提示的错误是:

              

如上图红线标出的。

token null is not for an application,不是由application提供的。

导致报这个错是在于new AlertDialog.Builder(mcontext),虽然这里的参数是AlertDialog.Builder(Context context)但我们不能使用getApplicationContext()获得的Context,而必须使用Activity,因为只有一个Activity才能添加一个窗体。(参考自http://www.cnblogs.com/ok-lanyan/archive/2011/10/12/2208378.html)


那么我们直接改为   AlertDialog.Builder(MainActivity.this)就可以了



0 0