2013-04-10 100 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();