-3

How can I call "getContent" inside "onCreate"? I am getting errors like

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();
  }
}
Mike
  • 3,200
  • 5
  • 22
  • 33

1 Answers1

0

In android you cann't perform any networking task on UI thread. so you will have perform Networking task on a Different thread. For this you can use normal java Threads but this is not a good approach in android. you should use Async Task.

You can follow any good tutorial on google.

vabhi vab
  • 419
  • 4
  • 11