8

I am getting an Runtime Exception:Can't create handler inside thread that has not called Looper.prepare() while displaying the Toast message in a worker thread.

I have a service (runs in a remote process) which creates an object. This object is responsible for connecting to a server in a thread. I get the response from the sever. I want to display the message from the server in the toast. At that time I getting this exception. I tried posting it in a Handler by using handler.post. But still i am getting the exception.

What should be the approach to avoid this.

Leos Literak
  • 8,805
  • 19
  • 81
  • 156
Shrikanth Kalluraya
  • 1,099
  • 1
  • 16
  • 34
  • [Look at this](http://www.google.com/search?client=ubuntu&channel=fs&q=that+has+not+called+Looper.prepare%28%29&ie=utf-8&oe=utf-8) – Adil Soomro Aug 25 '11 at 06:27

1 Answers1

15

Define a Handler like this:

 private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
              if(msg.arg1 == 1)
                    Toast.makeText(getApplicationContext(),"Your message", Toast.LENGTH_LONG).show();
        }
    }

Then put the following code where you need to show your toast message.

Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
jainal
  • 2,973
  • 2
  • 20
  • 18
  • 1
    Thanks jainal this solution worked :-) I had tried this solution earlier but i was creating the handler in the thread. Now i changed the position it worked :-) – Shrikanth Kalluraya Aug 25 '11 at 08:18
  • check this library `compile 'com.shamanland:xdroid-toaster:0.0.5'`, it doesn't require `runOnUiThread()` or `Context` variable, all routine is gone! just invoke `Toaster.toast(R.string.my_msg);` here is the example: https://github.com/shamanland/xdroid-toaster-example – Oleksii K. Jul 17 '14 at 10:14