3

In the following code I want to open the dialog box when the mIndex is 0.

The code is going in the 'if' part. But is not opening the dialog Box instead showing the following exception.

Code:

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(); } 

Exception:

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

2 Answers 2

1

Instead of

new AlertDialog.Builder(getApplicationContext()); 

Try using

new AlertDialog.Builder(MainActivity.this); 
Sign up to request clarification or add additional context in comments.

1 Comment

Okay Great! Code worked fine.
0

Try this

 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(); 

1 Comment

Okay Great! Code worked fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.