2016-07-05 51 views
-1

我正在做一些HTTP請求,並且我得到這個錯誤在我的logcat:android.view.ViewRootImpl $ CalledFromWrongThreadException:多線程錯誤在安卓CalledFromWrongThreadException

所致只有原來的線程創建一個視圖層次結構可以觸及其視圖。

這是我DoInBackground代碼:

public class AsyncClass extends AsyncTask { 
StringBuilder result = new StringBuilder(); 
String stream = null; 
public String rest_Url = "https://....." ; 

@Override 
protected Object doInBackground(Object[] params) { 
    HttpURLConnection client = null; 

    try { 
     URL url = new URL(rest_Url); 
     client = (HttpURLConnection) url.openConnection(); 
     client.setRequestMethod("GET"); 
     client.setDoOutput(true); 


     int responseCode = client.getResponseCode(); 
     switch (responseCode){ 
      case 200: 
       String success = "SUCCESS"; 
       System.out.println(success); 

       InputStream inputPost = new BufferedInputStream(client.getInputStream()); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputPost)); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        result.append(line); 
       } 
       stream = result.toString(); 
       MainActivity.textView.setText(stream); 
       break; 

      default: 
       String failure = "FAILURE"; 
       System.out.println(failure); 
       break; 
     } 


    } catch (IOException e) { 
     e.printStackTrace();} 

    finally { 
     if(client != null){ 
      client.disconnect(); 
     } 
    } 

    return null; 
}} 

你能幫助我嗎? 即使我評論MainActivity.textView.setText(stream);,我也遇到了這個問題。

+0

'MainActivity.textView'?你是否聲明你的TextView是靜態的? – Blackbelt

回答

1

的問題來自於行:

MainActivity.textView.setText(stream); 

你需要封送到主線程。類似的問題在這裏: Run Callback On Main Thread

+0

代替元帥,我使用'onPostExecute()'方法,thx daf btw – CSecchi

+0

不客氣(: – daf