【问题标题】:AsyncTask - using element by findviewbyid of different fragmentAsyncTask - 通过不同片段的 findviewbyid 使用元素
【发布时间】: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


【解决方案1】:

您必须先放大您的视图,然后再在其中查找内容。

 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() 仅在视图已经膨胀后才能工作

【讨论】:

  • 我用什么来代替“容器”?
  • 您的视图的父级
猜你喜欢
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多