0

Hello here is my code:

package pl.polskieszlaki.przewodnikjura;

public class JSONParser extends AsyncTask<String, Void, JSONArray> {
public JSONParser() {

}

@Override
protected JSONArray doInBackground(String... url) {
    return getJSONFromUrl(url[0]);
}

public JSONArray getJSONFromUrl(String inputUrl) {
    JSONArray jObj = null;
    String result = "";
    InputStream is = null;
    // Making HTTP request
    Log.d("ps","url: "+inputUrl);
    try {
        URL url = new URL(inputUrl);
        is=url.openStream();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        Log.v("RESULT: ", result);
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jObj = new JSONArray(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    //return jArray;
    return jObj;

}

}

I always get "Error in http connection android.os.NetworkOnMainThreadException" - why? I have AsyncTask.

Here is my code in Activity:

    JSONParser jParser = new JSONParser();
    Log.d("ps","1Pobieram url: "+url); 
    // getting JSON string from URL
    JSONArray json = jParser.getJSONFromUrl(url);
piernik
  • 3,507
  • 3
  • 42
  • 84
  • main thread is the ui thread. you get `NetworkOnMainThreadException` coz you are trying to do network related operation on the main ui thread which is not possible post honey comb. – Raghunandan Jul 03 '13 at 12:07

2 Answers2

1

you have to call execute() on the instance of JSONParser, instead of getJSONFromUrl() . The method getJSONFromUrl is synchronous:

Change

JSONArray json = jParser.getJSONFromUrl(url);

with

jParser.execute(url);

to retrieve the result, check my answer to this question

Community
  • 1
  • 1
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0
JSONParser jParser = new JSONParser();
Log.d("ps","1Pobieram url: "+url); 
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);

Replace this code to

JSONParser jParser = new JSONParser().execute(url);

In doInBackground store the result in global variable and use that one to update the UI

Srikanth
  • 584
  • 1
  • 6
  • 21