QuinnF
QuinnF

Reputation: 2169

How can I show a dialog on another context?

My android app needs to show a dialog after a delay. The problem is that by the time the dialog is displayed, the context may have changed.

How can I solve this problem?

My code right now looks like this:

class UpdateRunnable extends Runnable {
    private Context ctx;
    UpdateRunnable(Context ctx) {
        this.ctx = ctx
    }
    @Override
    public void run() {
        //throws exception: "Unable to add window -- token null is not for an application"
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx.getApplicationContext());
        builder.setTitle("Time to refresh data");
        builder.setMessage("Data needs updating");
        builder.show();
    }
}

class MyAvtivity extends AppCompatActivity {
    @override
    public void onCreate(...) {
        Handler updateHandler = new Handler();
        updateHandler.postDelayed(new UpdateRunnable(this), 10000);

        //do some stuff
        //start another activity
    }
}

Upvotes: 0

Views: 172

Answers (3)

faranjit
faranjit

Reputation: 1627

private Context ctx; 
UpdateRunnable(Activity activity) { this.activity = activity } 

@Override public void run() { 
    if(!activity.isFinishing()){ 
        AlertDialog.Builder builder = new AlertDialog.Builder(activity); 
        builder.setTitle("Time to refresh data"); 
        builder.setMessage("Data needs updating");
        builder.show(); 
    }
}

Upvotes: 0

ale.m
ale.m

Reputation: 883

AlertDialog.Builder doesn't work with ApplicationContext. That is why you are getting a bad token exception.

So you need to make sure that the context of your runnable is your current activity context, or try a different aproach like using a service with the logic of when to show the dialog inside, and make it notify the current activity that it should show the dialog, or use the service to start an activity with a Dialog.Theme instead of using an AlertDialog.

Upvotes: 1

snachmsm
snachmsm

Reputation: 19233

have you tried with ContextWrapper?

Upvotes: 0

Related Questions