내 서버에 JSON 파일 (towns.json)이 있고 앱에서 데이터를 읽으 려합니다. 그래서 UI 스레드를 차단하지 않기 위해 AsyncTask를 사용해야한다고 생각했습니다.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()이 예외를 throw :
org.json.JSONException : 문자의 0 입력의 끝 ... 정확히 내가 잘못
을 뭐하는 거지?
문제는 _sometimes_가이 오류를 throw합니다. (서버의 파일은 항상 사용 가능합니다). – user934779
오류가 발생하면 readTown 내용을 확인 했습니까? – marcinj
때때로 readTown의 내용이 결과를 반환하지 않습니다. 그것이 문제였습니다. – user934779