2013-04-10 91 views
-4

我有以下代码,对于一个线程。当我运行该应用程序时,出现以下异常。线程的执行处理程序

04-10 09:16:29.399: E/AndroidRuntime(14847): FATAL EXCEPTION: Thread-10 
04-10 09:16:29.399: E/AndroidRuntime(14847): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 
04-10 09:16:29.399: E/AndroidRuntime(14847): at android.os.Handler.<init>(Handler.java:121) 
04-10 09:16:29.399: E/AndroidRuntime(14847): at android.widget.Toast.<init>(Toast.java:76) 
04-10 09:16:29.399: E/AndroidRuntime(14847): at android.widget.Toast.makeText(Toast.java:251) 
04-10 09:16:29.399: E/AndroidRuntime(14847): at com.mobilevoiceapps.speeddial.Class_Add_Contact$1.run(Class_Add_Contact.java:88) 
04-10 09:16:29.399: E/AndroidRuntime(14847): at java.lang.Thread.run(Thread.java:1019) 

这里是我的代码:::

Thread myThread = new Thread(new Runnable(){ 
    @Override 
    public void run() 
    { 
     try 
     { 
      while(!isLoaded) 
      { 
       Toast.makeText(Class_Add_Contact.this, "Retrieving Contacts.. Please Wait !!!", Toast.LENGTH_LONG).show(); 
       wait(5000); 
      } 
     } 
     catch (Exception e) 
     { 

     } 
     finally{ 
      // Exception at below line 
      Toast.makeText(Class_Add_Contact.this, "Retrieving Contacts Complete", Toast.LENGTH_LONG).show(); 
     } 
    } 
}); 

myThread.start(); 

如何实现处理程序的代码?

+1

尝试runOnUiThread(新的Runnable(){ @覆盖 公共无效的run(){// UI码 }}); – 2013-04-10 04:07:15

+0

我在哪里做这个?在finally {}中。我对线程相当陌生。所以,如果你可以详细说明一下,这将是非常有帮助的 – 2013-04-10 04:10:24

+0

添加你的代码// UI代码 – 2013-04-10 04:18:46

回答

0

尝试

runOnUiThread(new Runnable() { @Override public void run() { 
    try 
     { 
      while(!isLoaded) 
      { 
       Toast.makeText(Class_Add_Contact.this, "Retrieving Contacts.. Please Wait  !!!", Toast.LENGTH_LONG).show(); 
       wait(5000); 
      } 
     } 
     catch (Exception e) 
     { 

     } 
     finally{ 
      // Exception at below line 
      Toast.makeText(Class_Add_Contact.this, "Retrieving Contacts Complete", Toast.LENGTH_LONG).show(); 
     } 
     }}); 

希望这可以帮助你。

+0

感谢您的帮助!我已经发布了答案。不管怎么说,还是要谢谢你 – 2013-04-10 04:19:09

0

这是我如何改变它,它的工作原理。

Thread myThread = new Thread(new Runnable(){ 
      Class_Add_Contact cladd = new Class_Add_Contact(); 

      @Override 
      public void run() 
      { 
       try 
       { 
        while(!isLoaded) 
        { 
         Toast.makeText(Class_Add_Contact.this, "Retrieving Contacts.. Please Wait !!!", Toast.LENGTH_LONG).show(); 
         wait(5000); 
        } 
       } 
       catch (Exception e) 
       { 

       } 
       finally{ 

        //Toast.makeText(Class_Add_Contact.this, "Retrieving Contacts Complete", Toast.LENGTH_LONG).show(); 

        cladd.runOnUiThread(new Runnable() { 
          public void run() { 
          Toast.makeText(Class_Add_Contact.this, "Retrieving Contacts Complete", Toast.LENGTH_SHORT).show(); 
          } 
         }); 
       } 
      } 
     }); 

     myThread.start();