Rob
Rob

Reputation: 16002

Android : application crashes with BadTokenException Error (trying to show AlertDialog)

I simply want to print an alert on the screen if there is no connection.

Here is what I did in my class that extends Activity.

if(isOnline()) { 
    // do stuff..
} else {
    Builder builder =  new AlertDialog.Builder(getApplicationContext());
    builder.setMessage("No connection.");
    builder.setCancelable(true);
    AlertDialog dialog = builder.create();
    dialog.show();
}

Then I tried to launch it with Debug, and got the following error :

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

Upvotes: 1

Views: 274

Answers (4)

Luna Kong
Luna Kong

Reputation: 3155

Replace the line

Builder builder =  new AlertDialog.Builder(getApplicationContext());

with

Builder builder =  new AlertDialog.Builder(YourActivityName.this);

Since you may need an Activity Context instead of Application Context.

Hope it helps.

Upvotes: 3

Richa
Richa

Reputation: 3193

Use yourActivityName.this instead of getApplicationContext();

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

use

 Builder builder =  new AlertDialog.Builder(Your_Current_Activity.this);

instead of

 Builder builder =  new AlertDialog.Builder(getApplicationContext());

because you will need to pass Current Activity Context to show AlertDialog instead of Application Context

Upvotes: 4

Usman Kurd
Usman Kurd

Reputation: 7023

try to use classname.this other than getApplicationContext() this some time cause issues

if(isOnline()) { 
    // do stuff..
} else {
    Builder builder =  new AlertDialog.Builder(getApplicationContext());
    builder.setMessage("No connection.");
    builder.setCancelable(true);
    AlertDialog dialog = builder.create();
    dialog.show();
}

Upvotes: 1

Related Questions