你好是我的代碼:爲什麼在主線程中?這裏
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。
這是我在活動代碼:
JSONParser jParser = new JSONParser();
Log.d("ps","1Pobieram url: "+url);
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
主線程UI線程。你得到'NetworkOnMainThreadException'因爲你正試圖做主要的UI線程上的網絡相關的操作,這是不可能的後蜜蜂。 – Raghunandan