Reputation: 16002
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
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
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
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