您的位置:首页 > 移动开发

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

2010-12-25 01:23 483 查看
错误产生:

Java代码

private Context mcontext;

@Override

protected void onCreate(Bundle savedInstanceState) {mcontext = getApplicationContext();

System.out.println("mcontext=" + mcontext);

}

private Context mcontext;

@Override
protected void onCreate(Bundle savedInstanceState) {mcontext = getApplicationContext();
System.out.println("mcontext=" + mcontext);

}


Java代码

new AlertDialog.Builder(mcontext)

.setIcon(android.R.drawable.ic_dialog_alert)

.setTitle("Warnning")

.setMessage(

"You forget to write the message. Do you want to fill out it ??")

.setPositiveButton("Yes", positiveListener).setNegativeButton(

"No", negativeListener).create().show();

new AlertDialog.Builder(mcontext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Warnning")
.setMessage(
"You forget to write the message. Do you want to fill out it ??")
.setPositiveButton("Yes", positiveListener).setNegativeButton(
"No", negativeListener).create().show();


导致报这个错是在于new AlertDialog.Builder(mcontext),虽然这里的参数是AlertDialog.Builder(Context context)但我们不能使用getApplicationContext()获得的Context,而必须使用Activity,因为只有一个Activity才能添加一个窗体。

解决方法:将new AlertDialog.Builder(Context context)中的参数用Activity.this(Activity是你的Activity的名称)来填充就可以正确的创建一个Dialog了。

Java代码

new AlertDialog.Builder(MyActivity.this)

.setIcon(android.R.drawable.ic_dialog_alert)

.setTitle("Warnning")

.setMessage(

"You forget to write the message. Do you want to fill out it ??")

.setPositiveButton("Yes", positiveListener).setNegativeButton(

"No", negativeListener).create().show();

new AlertDialog.Builder(MyActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Warnning")
.setMessage(
"You forget to write the message. Do you want to fill out it ??")
.setPositiveButton("Yes", positiveListener).setNegativeButton(
"No", negativeListener).create().show();


问题得以解决!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐