我是 Android 的初学者,我正在编写一个简短的程序来从 URL 下载 JSON 提要并解析它。我使用 AsyncTask 进行下载。
doInBackground() 部分似乎运行良好。然后我将断点设置为 onPostExecute(),它甚至可以停在parseJSON(result)
,并且“结果”显示下载的正确 json 字符串。但是当我尝试进入时parseJSON(result)
,它不会正确地进入函数(或者直接抛出 JSONException 或者进入一些随机行parseJSON(result)
)。
从 DDMS 日志中,它也没有显示任何有价值的信息。
我怎样才能找到问题所在?是我用onPostExecute()
错了,还是parseJSON()
有问题?
public class MainActivity extends Activity {
private listItem[] items;
public class listItem {
String title;
String description;
String imageHref;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new listItem[50];
new DownloadJsonFeed().execute("http://dl.dropbox.com/u/10168342/facts.json");
}
private class DownloadJsonFeed extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
return downloadUrl(params[0]);
} catch (IOException e) {
return "Unable to retrieve json feed. URL may be invalid.";
}
}
@Override
protected void onPostExecute(String result) {
try {
parseJSON(result); // Here !!!!!!
} catch (JSONException e) {
}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
} finally {
if (is != null) {
is.close();
}
}
}
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = new JSONArray(rows);
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}