0

您好,这是我的代码:

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;

}

}

我总是收到“http 连接 android.os.NetworkOnMainThreadException 错误” - 为什么?我有异步任务。

这是我在活动中的代码:

    JSONParser jParser = new JSONParser();
    Log.d("ps","1Pobieram url: "+url); 
    // getting JSON string from URL
    JSONArray json = jParser.getJSONFromUrl(url);
4

2 回答 2

1

您必须调用execute()JSONParser 的实例,而不是getJSONFromUrl(). 该方法getJSONFromUrl是同步的:

改变

JSONArray json = jParser.getJSONFromUrl(url);

jParser.execute(url);

要检索结果,请查看我对这个问题的回答

于 2013-07-03T12:06:02.493 回答
0
JSONParser jParser = new JSONParser();
Log.d("ps","1Pobieram url: "+url); 
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);

将此代码替换为

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

在 doInBackground 中将结果存储在全局变量中并使用该变量来更新 UI

于 2013-07-03T12:09:20.493 回答