2012-02-25 53 views
2

當我嘗試從網站讀取單行文本時,出現錯誤(NetworkOnMainThreadException)。我嘗試了一些東西,但目前爲止沒有任何工作。所以這裏是代碼,如果有人可以幫助。在清單中,我有互聯網許可,所以他不應該成爲問題。NetworkOnMainThreadException從網上讀取時

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class Weather extends Activity { 

    Button button; 
    TextView t; 
    String result; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.weather); 

     t = (TextView)findViewById(R.id.textView1); 

    } 

    public void myButtonClickHandler (View view) throws ClientProtocolException, IOException { 
     result = getContentFromUrl("http://url.com"); 
     t.setText(result); 
    } 

    public static String getContentFromUrl(String url) throws ClientProtocolException, IOException { 

     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     HttpResponse response; 

     response = httpClient.execute(httpGet); 
     HttpEntity entity = response.getEntity(); 

     if(entity != null) { 

      InputStream inStream = entity.getContent(); 

      String result = Weather.convertStreamToString(inStream); 
      inStream.close(); 

      return result; 
     } 

     return null; 

    } 

    private static String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 

     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
} 

回答

7

不在主線程中使用網絡活動。僅針對面向Honeycomb SDK或更高版本的應用程序引發此例外。在單獨的線程中執行所有與網絡相關的任務(使用處理器循環或runOnUiThread)。你的問題將得到解決。

+0

恩,請問我能舉個例子嗎? – HyperX 2012-02-25 08:58:47

+1

你可以在http://www.vogella.de/articles/AndroidPerformance/article.html和http://www.xoriant.com/blog/mobile-application-development/android-async-task.html以及http://developer.android.com/resources/articles/painless-threading.html – 2012-02-25 10:15:26

4

要麼你可以將它移動到後臺線程,或者如果你只是想消除這種錯誤只添加這在你的onCreate():

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

    StrictMode.setThreadPolicy(policy); 

不要忘記添加Internet權限清單中:

<uses-permission android:name="android.permission.INTERNET"/>