在以下代码中,我想在mIndex
为0时打开对话框。
代码进入'如果'部分。但是没有打开对话框而是显示以下异常。
代码:
mIndex = (mIndex+1)%mQuestionBank.length;
if(mIndex == 0 )
{
Log.d("Quizzler", "Inside IF");
AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
alert.setTitle("Game Over");
alert.setCancelable(false);
alert.setMessage("Your score is "+mScore);
alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
例外:
FATAL EXCEPTION: main
Process: com.londonappbrewery.quizzler, PID: 11560 android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:714)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:316)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at com.londonappbrewery.quizzler.MainActivity.updateQuestion(MainActivity.java:100)
at com.londonappbrewery.quizzler.MainActivity.access$100(MainActivity.java:16)
at com.londonappbrewery.quizzler.MainActivity$1.onClick(MainActivity.java:69)
at android.view.View.performClick(View.java:5609)
at android.view.View$PerformClick.run(View.java:22263)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
答案 0 :(得分:1)
而不是
new AlertDialog.Builder(getApplicationContext());
尝试使用
new AlertDialog.Builder(MainActivity.this);
答案 1 :(得分:0)
试试这个
AlertDialog.Builder alert = new AlertDialog.Builder(YourActivity.this);
alert.setTitle("Game Over");
alert.setCancelable(false);
alert.setMessage("Your score is "+mScore);
alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog=alert.create();
alertDialog.show();