Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting Toast message from a Thread

My application launches a thread to query the web for some data. I want to display a Toast message when nothing is found, but my application always crashes.

I've tried using the application Context from within the thread, like so:

Toast.makeText(getApplicationContext(), "testttt", Toast.LENGTH_LONG).show();

I've also tried creating a Runnable with the Toast call and calling runOnUiThread(runnable) from the Thread (the Toast call in this runnable uses the Activity as the first parameter).

Does anyone have any ideas on how to accomplish this?

like image 548
Andrew Avatar asked Nov 17 '10 22:11

Andrew


1 Answers

Try to post inside to a Handler object.

final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
    public void run() {
        Toast(this, message, duration).show();
    }

new Thread() {
    public void run() {
        mHandler.post(mUpdateResults);
    }
}.start();
like image 187
davidcesarino Avatar answered Oct 12 '22 23:10

davidcesarino