我想从这个 url http://inspirontrance.com/tpb.json解析 JSON 数据。我的代码在没有 AsyncTask 但启用 AsyncTask 的情况下工作,加载一定次数后应用程序崩溃。虽然我的代码看起来不错,但不知何故,应用程序在异步过程中冻结了。
这是我的代码,
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://inspirontrance.com/tpb.json";
// JSON Node names
private static final String TAG_UPLOADS = "uploads";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DATE = "date";
ProgressDialog pDialog;
// JSONArray
JSONArray uploads = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new MyAsyncTask().execute(url);
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> UploadsList = new ArrayList<HashMap<String, String>>();
@Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Uploads
uploads = json.getJSONArray(TAG_UPLOADS);
// looping through All Uploads
for (int i = 0; i < uploads.length(); i++) {
JSONObject c = uploads.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
UploadsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return UploadsList;
}
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(this, result,
R.layout.list_item,
new String[] { TAG_NAME, TAG_ID, TAG_DATE }, new int[] {
R.id.name, R.id.id, R.id.date });
setListAdapter(adapter);
}
}