我从Fragment1调用AsyncTask类并尝试在Fragment2的listview中存储doInBackground()的结果。
但是当我使用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);
}
答案 0 :(得分:0)
在查找内容之前,您必须给视图充气。
MyCartFragment mcf=new MyCartFragment(); //2nd Fragment
View v= inflater.inflate(R.layout.fragment2, container, false); // <= inflate your view
cartlistview=(ListView)v.findViewById(R.id.listView1); // v is not null anymore
Fragment.getView()
只有在视图已经膨胀后才能生效