从其他类调用静态字符串onCreate

时间:2016-03-08 14:44:43

标签: java android

如何在“onCreate”中调用“getContent”? 我收到了像

这样的错误
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();
  }
}

1 个答案:

答案 0 :(得分:0)

在android中你不能在UI线程上执行任何网络任务。所以你将在不同的线程上执行网络任务。为此你可以使用普通的java Threads,但这不是android中的好方法。你应该使用异步任务。

你可以在google上关注任何好的教程。