這一個已經啃了我一會兒,我創建了一個AsyncTask來從我的數據庫中提取產品,我希望它們能夠顯示在listView中,不會出現構建錯誤,並且LogCat會打印出來JSON的代碼,但沒有打印到ListViewJSON不打印到ListView
private class LoadJsonTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>> > {
ProgressDialog dialog ;
protected void onPreExecute() {
dialog = ProgressDialog.show(GetProducts.this ,"Loading","Please wait");
}
protected ArrayList<HashMap<String, String>> doInBackground (String... params) {
return doGetJson();
}
protected void onPostExecute(ArrayList<HashMap<String, String>> mylist) {
dialog.dismiss();
}
}
public ArrayList<HashMap<String, String>> doGetJson() {
JSONObject json = null;
ArrayList<String> mylist = new ArrayList<String>();
Functions uf = new Functions();
json = uf.getProducts();
try {
//the array title that you parse
JSONArray category = json.getJSONArray("products");
ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < category.length() ; i++) {
JSONObject c = category.getJSONObject(i);
String name = c.getJSONObject("name").toString();
String products = c.getJSONObject("price").toString();
items.add(name);
items.add(products);
Log.d(name,"Output");
}
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, items);
ListView ProductList = (ListView)findViewById(R.id.listView1);
mArrayAdapter.notifyDataSetChanged();
ProductList.setAdapter(mArrayAdapter);
} catch (JSONException e) { }
return null;
}
的logcat的打印出
1-05 23:08:09.732: E/JSON(17841): {"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee1","price":"4.00","image":"http:\/\/test.com"}}{"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee2","price":"5.00","image":"http:\/\/test2.com"}}
但正如我說什麼被打印到我的ListView它只是保持空白。
您好,感謝回答。當你說「那個代碼」時,你的意思是for循環還是for循環之後的所有內容? – user2960452
我更新了我的答案,以便更具體。 –
嗨,當我移動到onPostExceute它告訴我,「項目」無法找到 - doInBackground需要返回項目嗎? – user2960452