hcemp
hcemp

Reputation: 119

Toast can't be used in new runnable?

as the title,i was used toast in runnable but there is an error my code:

public Runnable backgroud=new Runnable(){

    public void run() {
        // TODO Auto-generated method stub
        try
        {
            while(!Thread.interrupted())
            {
        String msg="this is a test";
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        Thread.sleep(1000);
            }
        }
        catch(InterruptedException c)
        {
            c.printStackTrace();
        }
    }

};

Upvotes: 0

Views: 4504

Answers (2)

Sunil Pandey
Sunil Pandey

Reputation: 7102

you can not use toast directly in other thread but there is a solution you create your msgHandler

 mHandler = new Handler() { 
              @Override public void handleMessage(Message msg) { 
                 String mString=(String)msg.obj;
                 Toast.makeText(this, mString, Toast.LENGTH_SHORT).show();
              }
          };

after that you pass message from your thread

 new Thread(new Runnable() {

                           @Override
                           public void run() {
                                   while(!Thread.interrupted())
                                   {

                                       Message msg=new Message();
                                       msg.obj="your text";
                                       mHandler.sendMessage(msg);
                                        try {
                                            Thread.sleep(100);
                                        } 
                                        catch (InterruptedException e) {
                                           e.printStackTrace();
                                        }
                                   }
                           }
                   }).start();

Upvotes: 7

Dre
Dre

Reputation: 4329

You cannot use Toasts ( or anything that shows something on the UI ) from other threads.

See runOnUiThread

Upvotes: 2

Related Questions