2014-03-02 36 views
0

我想從AONAWARE.COM一些WordDefinition,我試圖parse XML這樣的:爲什麼android.os.NetworkOnMainThreadException ocurse

protected String getWordDefinition(Context context, String word) { 
    StringBuilder wordDefination = new StringBuilder(); 
    HttpClient httpClient = new DefaultHttpClient(); 
    StringBuilder queryString = new StringBuilder(URL); 
    queryString.append(word); 
    HttpGet request = new HttpGet(queryString.toString()); 
    HttpResponse httpResponse; 
    try { 
     httpResponse = httpClient.execute(request); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     BufferedReader bufferedReader = new BufferedReader(
       new InputStreamReader(httpEntity.getContent())); 
     String readLineString = ""; 
     while ((readLineString = bufferedReader.readLine()) != null) { 
      wordDefination.append(readLineString + "\n"); 
      Log.e(AONAWARE_TAG, "Init " + wordDefination); 
     } 
     return (wordDefination.toString()); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
     return null; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

Successful一或兩次從getWordDefinition獲取數據,但現在突然我得到這個android.os.NetworkOnMainThreadException及以下LogCat

03-02 17:11:31.601: W/dalvikvm(614): threadid=1: thread exiting with uncaught exception (group=0x40a13300) 
03-02 17:11:31.631: E/AndroidRuntime(614): FATAL EXCEPTION: main 
03-02 17:11:31.631: E/AndroidRuntime(614): android.os.NetworkOnMainThreadException 
03-02 17:11:31.631: E/AndroidRuntime(614): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 
03-02 17:11:31.631: E/AndroidRuntime(614): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 
03-02 17:11:31.631: E/AndroidRuntime(614): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
03-02 17:11:31.631: E/AndroidRuntime(614): at java.net.InetAddress.getAllByName(InetAddress.java:214) 
03-02 17:11:31.631: E/AndroidRuntime(614): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 
. 
. 
. 

爲什麼呢?如何解決這個Exception

回答

1

您必須在工作線程中執行網絡進程,這是使用異步任務的最佳方式。

2

您無法在主線程(UI線程)上執行網絡操作。這是一種合理的行爲,因爲這種操作可能會持續很長時間,所以您的UI可能會凍結。你應該總是在不同的線程中進行長時間的操作。考慮使用AsyncTask

相關問題