2014-09-04 49 views
0

我在獲取線程的Internet資源時出錯。線程出錯

我得到的logcat此錯誤:

09-04 21:05:32.916 1480-1493/abc.digicare.sms1 E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-78 
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 
     at android.os.Handler.<init>(Handler.java:121) 
     at android.widget.Toast$TN.<init>(Toast.java:317) 
     at android.widget.Toast.<init>(Toast.java:91) 
     at android.widget.Toast.makeText(Toast.java:233) 
     at abc.digicare.sms1.MyActivity$1.run(MyActivity.java:45) 
     at java.lang.Thread.run(Thread.java:856) 

我的代碼是這樣的:從調用一個按鈕,點擊此功能。

public void GetData(View v) { 
    Toast.makeText(getApplicationContext(), "first", Toast.LENGTH_SHORT).show(); 
    p=ProgressDialog.show(getApplicationContext(),"Digicare","Wait . . ."); 

    try { 
     Runnable myrun = new Runnable() { 
      @Override 
      public void run() { 

       String acc = ""; 
       if (chckbx_cus.isChecked() && !(chckbx_ven.isChecked()) && !(chckbx_emp.isChecked())) { 
        acc = "cus"; 
       } else if (chckbx_ven.isChecked() && !(chckbx_cus.isChecked()) && !(chckbx_emp.isChecked())) 

       Toast.makeText(getApplicationContext(), acc, Toast.LENGTH_SHORT).show(); 

       final String facc = acc; 

       GetList GL = new GetList(); 
       //Toast.makeText(getApplicationContext(),txt_ip.getText(),Toast.LENGTH_SHORT).show(); 
       obj = GL.GetAccounts(getApplicationContext(), facc, "GetAccounts", "192.168.1.111"); 
       mhandler.sendEmptyMessage(0); 
      } 

     }; 
     Thread th = new Thread(myrun); 
     th.start(); 

    } catch (Exception e) { 
     Toast.makeText(getApplicationContext(), "from here " + e.toString(), Toast.LENGTH_LONG).show(); 
    } 

    mhandler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      p.dismiss(); 
     } 
    }; 
} 

這是從其他類調用的函數是從asp.net web服務

回答

0

獲取數據看來你正試圖從後臺線程顯示吐司。在try-catch塊之前移動Handler創建代碼,並使用final修飾符,以便可以從Runnable中訪問處理程序。然後在可運行呼叫中

mhandler.post(new Runnable() { 
    public void run() { 
     Toast.makeText(getApplicationContext(), acc, Toast.LENGTH_SHORT).show(); 
    } 
});