9
String response = getResultForRequest(url);

Where 'url' is JSON formatted which return bunch of data using http GET method.

public static String getResultForRequest(String urlString)
        throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection urlConnection = (HttpURLConnection) url
            .openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.connect();

    InputStream is = urlConnection.getInputStream();
    if (is == null)
        return null;
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = null;
    try {
        while ((line = br.readLine()) != null)
            sb.append(line);
    } finally {
        br.close();
        is.close();
    }

    return sb.toString();
}

I can not fetch JSON formatted data from 'url' which i have passed in getResultForRequest(url) method.I got an error in urlConnection.connect();. Internet Permission is also given in AndroidManifest.xml file.

Here is my Log.

10-09 13:27:35.264: E/AndroidRuntime(9984): FATAL EXCEPTION: main
10-09 13:27:35.264: E/AndroidRuntime(9984): java.lang.RuntimeException: Unable to start activity ComponentInfo{}: android.os.NetworkOnMainThreadException
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.os.Looper.loop(Looper.java:137)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.ActivityThread.main(ActivityThread.java:4898)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at java.lang.reflect.Method.invokeNative(Native Method)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at java.lang.reflect.Method.invoke(Method.java:511)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at dalvik.system.NativeStart.main(Native Method)
10-09 13:27:35.264: E/AndroidRuntime(9984): Caused by: android.os.NetworkOnMainThreadException
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at com.csoft.foursquare.FoursquareService.getResultForRequest(Service.java:564)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at com.csoft.foursquare.FoursquareService.getUserDetails(Service.java:376)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at com.csoft.checkin.CheckinHistoryActivity.onCreate(HistoryActivity.java:52)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.Activity.performCreate(Activity.java:5206)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
10-09 13:27:35.264: E/AndroidRuntime(9984):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
10-09 13:27:35.264: E/AndroidRuntime(9984):     ... 11 more

Thanks in Advance.

Dhruv
  • 1,814
  • 3
  • 20
  • 37
  • 2
    Please close this question, it has been asked and answered a zillion times – njzk2 Oct 09 '13 at 08:22
  • To download JSON you can use "Volley" which will do the work for you http://www.kpbird.com/2013/05/volley-easy-fast-networking-for-android.html – An-droid Oct 09 '13 at 08:28

3 Answers3

33

Add this in your onCreate():

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

Use the above as a temporary solution. Otherwise use thread or asynctask.

fida1989
  • 3,234
  • 1
  • 26
  • 30
  • 5
    Please, avoid the code above.. at docs you will see: "it's heavily discouraged" about the StrictMode... seems that you are doing some network request on the main thread, you just need to move the request or the respose.getEntity to an AsyncTask, this is the right solution to your problem.. – Guilherme Oliveira Jun 05 '14 at 14:53
  • I said that already in the answer. Only to use the given code as temporary solution, otherwise to use thread/asynctask. – fida1989 Jun 08 '14 at 10:04
  • 1
    Thanks you save my time. – Arbaz.in May 14 '18 at 13:29
14

You're attempting to make a network connection on the main (UI) thread. This is not allowed in Android since it will halt the entire UI until you get a response from the server.

Try using AsyncTask, or performing the connection on a separate thread.

Hope this helps.

Gil Moshayof
  • 16,433
  • 4
  • 44
  • 57
3

NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.

You should call method on asynctask then only code will work. To avoid it you should call it on another thread. Hence asynctask is better.

http://android-developers.blogspot.in/2009/05/painless-threading.html

http://android-er.blogspot.in/2012/04/androidosnetworkonmainthreadexception.html

http://www.lucazanini.eu/2012/android/the-android-os-networkonmainthreadexception-exception/?lang=en

here is link that illustrates how to use asynctask

Hariharan
  • 28,756
  • 7
  • 51
  • 55
  • thanks @Tamilan. I am done with AsyncTask.But the problem is that when i run this code then in above 4.0 then data can not be fetch from the url. But in Gingerbread it shows perfectly means data should be display finely. I can not understand what's problem happening. – Dhruv Oct 09 '13 at 12:08
  • this exception is thrown if the target sdk version is >= 14 or >=15 (i'm not sure, i'm sorry), only – Sandra Nov 22 '13 at 12:31
  • @Sandra may be it'll give for all – Hariharan Nov 22 '13 at 12:35
  • I know that when my app was set to target sdk 9, it did not give an exception. But set to 14, id did. – Sandra Nov 22 '13 at 12:59
  • @Sandra then you should use asynctask. – Hariharan Nov 22 '13 at 15:28