【发布时间】:2016-10-31 10:25:20
【问题描述】:
我正在从 Fragment1 调用 AsyncTask 类并尝试将 doInBackground() 的结果存储在 Fragment2 的列表视图中。
但是当我使用 Fragment2 的视图来访问类似的元素时
cartlistview=(ListView)v.findViewById(R.id.listview1);
它抛出 空指针异常,说明 v 为空。
我在 onPosteExecute() 函数中写了存储代码
protected void onPostExecute(String result) {
MyCartFragment mcf=new MyCartFragment(); //2nd Fragment
View v=mcf.getView();
cartlistview=(ListView)v.findViewById(R.id.listView1); // ERROR HERE
// Code starting from here is not causing any problems - ignoreable.
Cursor res=databaseHelper.onView();
int len=res.getCount();
listCartItems = new ArrayList<CartItems>();
listCartItems.add(new CartItems(9,"Item Name", "Quantity", "Price","Delete"));
if(len==0)
{
//Toast.makeText(this.getContext(),"Cart is Empty.",Toast.LENGTH_SHORT).show();
statusOfCart=false;
}
else {
while (res.moveToNext()) {
int id=res.getInt(0);
String itemname = res.getString(1).toString(); // 0 is id, 1 is name, 2 is qty, 3 price
String itemqty = Integer.toString(res.getInt(2));
String itemprice = Integer.toString(res.getInt(3));
listCartItems.add(new CartItems(id,itemname, itemqty, itemprice,"X"));
}
}
CartListAdapter cartListAdapter = new CartListAdapter(mcf.getContext(),R.layout.cartlist_layout, listCartItems);
cartlistview.setAdapter(cartListAdapter);
}
【问题讨论】:
-
鉴于您必须使用
xml文件而不是java文件进行膨胀 -
为什么要在一个 Fragment 中实现 AsyncTask 并在另一个 Fragment 中显示结果?
-
将商品数据插入到 add-to-cart-fragment(第一个片段)中的 db 表中,并在 cart-fragment(第二个片段)中显示 db 表的结果。我是新手。请告诉我是否有更好的方法。
标签: android listview android-asynctask