开发者

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开发者_如何学Go have any ideas on how to accomplish this?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜