2016-03-08 68 views
-3

如何在「onCreate」中調用「getContent」? 我越來越喜歡從其他類調用靜態字符串onCreate

E/AndroidRuntime: FATAL EXCEPTION: main 
java.lang.RuntimeException: Unable to start activity: android.os.NetworkOnMainThreadException 
Caused by: android.os.NetworkOnMainThreadException 

main.java

protected void onCreate(Bundle savedInstanceState) { 
    Log.d("URL", HttpUtils.getContents("http://google.com")); 
} 

HttpUtils.java

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLConnection; 

public class HttpUtils { 

    public static String getContents(String url) { 
     String contents =""; 

    try { 
     URLConnection conn = new URL(url).openConnection(); 

     InputStream in = conn.getInputStream(); 
     contents = convertStreamToString(in); 
    } catch (MalformedURLException e) { 
     Log.v("MALFORMED URL EXCEPTION"); 
    } catch (IOException e) { 
     Log.e(e.getMessage(), e); 
    } 

    return contents; 
} 

private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException { 

     BufferedReader reader = new BufferedReader(new  
           InputStreamReader(is, "UTF-8")); 
     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(); 
    } 
} 
+5

http://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception – CommonsWare

回答

0

在Android版上水溼UI線程執行任何任務的網絡錯誤。所以你將在不同的線程上執行聯網任務。爲此,您可以使用普通的Java線程,但這在Android中不是一個好方法。你應該使用異步任務。

你可以在谷歌上關注任何好的教程。

相關問題