Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Toast.makeText().show() definitely needs to be run on the UI thread.

You should probably use an AsyncTask like Octavian Damiean mentioned, but here's some code using runOnUiThread if you're set on using that:

    public void showToastFromBackground(final String message) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        }
    });
}

Try implementing a class extending "Handler" in your Activity class and send a Message to it from the other thread. Explained more in detail here:

http://www.anddev.org/the_pizza_timer_-_threading-drawing_on_canvas-t126.html

And please, when asking a question like this, include the stack trace you are getting.

If you're running the Handler from your Activity class, you can set the context by just referencing the .this of your Activity like so:

final Runnable showToastMessage = new Runnable() {
    public void run() {
        Toast.makeText(YourActivity.this, "Message", Toast.LENGTH_SHORT).show();
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top