Posting Toast message from a Thread

Andrew picture Andrew · Nov 17, 2010 · Viewed 26.6k times · Source

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?

Answer

davidcesarino picture davidcesarino · Nov 18, 2010

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