为什么在主线程?

时间:2013-07-03 12:03:24

标签: android android-asynctask

你好,这是我的代码:

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错误” - 为什么? 我有AsyncTask。

以下是我在Activity中的代码:

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

2 个答案:

答案 0 :(得分:1)

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

更改

JSONArray json = jParser.getJSONFromUrl(url);

jParser.execute(url);

要检索结果,请检查我对此question

的回答

答案 1 :(得分: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