FAQS


Show toast message inside run method of Thread.

Views: 9488  |   Date: 2013-08-31 04:55:46

I am using a thread and want to show a Toast message to user but when using Toast inside run method of thread getting force close error.


   
Thread background = new Thread(new Runnable() {
public void run() {
try {
// Got Run time error at this line
Toast.makeText(getBaseContext(),"Iam inside thread",Toast.LENGTH_SHORT).show();
}
catch (Throwable t)
{
// Got Run time error at this line
Toast.makeText(getBaseContext(),"URL exeption!"+t,Toast.LENGTH_SHORT).show();
}

Answer 1

Toast will always show in UI Thread.
You have got error beacause new Thread will run seperate from UI Thread. you are try to show Toast inside a Thread seperate from UI Thread.

Use this code :

Using runOnUiThread call make If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

   
Thread background = new Thread(new Runnable() { 
  public void run() {
    try {
              // Now Again Toast is running in UI Thread
              
              runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getBaseContext(),"Iam inside thread",Toast.LENGTH_SHORT).show();
                    }
                });
        } 
     catch (Throwable t) 
      {
          // Now Again Toast is running in UI Thread
              
          runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getBaseContext(),"URL exeption!"+t,Toast.LENGTH_SHORT).show();
                }
            });
         
      }	

 
Submit Your Answer
  |  
 
 
 

Preview :