这个已经啃了我一段时间了,我已经创建了一个AsyncTask来从我的数据库中提取产品,我希望它们显示在listView中没有出现构建错误,LogCat打印出JSON代码但是什么都没有打印到列表视图
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上没有任何内容,它只是空白。
答案 0 :(得分:0)
您在ArrayAdapter
创建ListView
并在onPostExecute
上设置的代码应该在UI线程上执行(来自 ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, items);
ListView ProductList = (ListView)findViewById(R.id.listView1);
ProductList.setAdapter(mArrayAdapter);
)。:
doInBackground
您无法在后台线程上执行此操作。
您已经返回了信息的HashMap,因此您只需将该代码移出onPostExecute
并移至notifyDataSetChanged
。
此外,您可以删除对HashMap<String, String>
的调用,因为这是初始数据加载。所以我会做出这些改变:
ArrayList<String>
的任何地方
return items
ArrayList<String>
(来自步骤1),因此您现在可以使用此参数来构建适配器。答案 1 :(得分:0)
String[] itemsArray = items.toArray(new String[items.size()]); // convert list to array
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, itemsArray);
ListView ProductList = (ListView)findViewById(R.id.listView1);
ProductList.setAdapter(mArrayAdapter); // swap the last two lines like this
mArrayAdapter.notifyDataSetChanged();
我猜这应该可以解决你的问题
更新了代码