我的服务器上有一个 JSON 文件(towns.json),在我的应用程序中,我希望从那里读取数据。所以我想我应该使用 AsyncTask 来不阻塞 UI 线程。我这样做如下:
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 处输入结束...
我到底做错了什么?