我有一个JSON文件(towns.json)坐在我的服务器上,在我的应用程序中,我希望从那里读取数据。 所以我想通了,我应该使用AsyncTask不阻止UI线程。我这样做如下:Android:在AsyncTask中发布JSON
private class GetTowns extends AsyncTask<String, String, Void> {
protected void onPreExecute() {}
@Override
protected Void doInBackground(String... params) {
String readTown = readFeed(ScreenStart.this, "http://server.com/towns.json");
try {
JSONArray jsonArray = new JSONArray(readTown);
town = new ObjectTown[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
town[i] = new ObjectTown();
town[i].setId(Integer.parseInt(jsonObject.getString("id")));
town[i].setName(jsonObject.getString("name"));
town[i].setLat(Double.parseDouble(jsonObject.getString("latitude")));
town[i].setLon(Double.parseDouble(jsonObject.getString("longitude")));
}
} catch (Exception e) {
Log.i("Catch the exception", e + "");
}
return null;
}
protected void onPostExecute(Void v) {}
}
而且readFeed()函数在这里:
public static String readFeed(Context context, String str) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(str);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content, "ISO-8859-1"));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
它的工作原理有时 ...但过一段时间,在doInBackground()抛出此异常:
org.json.JSONException:在字符的输入0结束......
我究竟做错了什么?
问题是,它只有_sometimes_抛出这个错误! (服务器上的文件始终可用)。 – user934779 2012-04-18 16:01:29
当错误发生时检查了readTown内容吗? – marcinj 2012-04-18 16:29:23
有时候,readTown的内容不会返回结果。这是问题。 – user934779 2012-04-18 17:33:38