【发布时间】:2016-11-01 06:40:05
【问题描述】:
我有 3 个碎片。 (主页、菜单、购物车)
当用户点击菜单片段中的项目时,点击的项目进入一个 SQLite 表(使用 INSERT QUERY)。
在购物车片段中,我使用选择查询来显示用户从菜单片段中选择的项目。
所以,这一切都在发生。
问题:
- 在菜单片段上:用户单击项目并将其添加到购物车(插入成功)
- 用户继续使用 CART FRAGEMENT。未显示在购物车片段中的更新值
- 现在,如果用户转到其他片段,然后返回,则会显示更新的值。
快照:
- 用户从菜单片段将“Sada Uthappa”项目添加到购物车。
- 用户现在转到购物车片段,它显示为空。
- 用户转到其他片段(如 HOME、MENU),然后转到 CART 片段。 瞧。更新后的结果。
要获取 CART FRAGMENT 中的更新数据,我必须单击 HOME 片段,然后单击 MENU 片段,然后单击 CART 片段。
菜单片段代码:
这里是菜单片段的代码:我在添加到购物车按钮上调用这个方法
public void onAddToCart(){
databaseHelper.onCreate();
success=databaseHelper.onInsert(iname.getText().toString(),qty.getText().toString(),t11.getText().toString());
Toast.makeText(getContext(),"Row id affected : "+success,Toast.LENGTH_SHORT).show();
}
这是来自 DatabaseHelper 类的 onInsert() 代码:
public long onInsert(String itemName,String qty,String price){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentvalue=new ContentValues();
contentvalue.put("NAME",itemName);
contentvalue.put("QTY",Integer.parseInt(qty));
contentvalue.put("PRICE",Integer.parseInt(price));
long result=db.insert(table,null,contentvalue);
return result;
}
购物车片段代码:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_mycart,container,false);
cartlistview=(ListView)view.findViewById(R.id.listView1);
db=new DatabaseHelper(this.getContext());
db.onCreate();
Cursor res=db.onView();
int len=res.getCount();
listCartItems = new ArrayList<CartItems>();
listCartItems.add(new CartItems(0,"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)) ;
Toast.makeText(this.getContext(),itemname,Toast.LENGTH_SHORT).show();
listCartItems.add(new CartItems(id,itemname, itemqty, itemprice,"X"));
}
}
CartListAdapter cartListAdapter = new CartListAdapter(getContext(), R.layout.cartlist_layout, listCartItems);
cartlistview.setAdapter(cartListAdapter);
return view;
}
【问题讨论】:
-
在
onCreateViewofCartFragment中记录一些信息。当您在MenuFragment时检查日志。你会知道自己发生了什么 -
更新后您可能没有重新加载片段。或者您可以简单地重新查询表格并再次显示其内容。
-
如何重新加载片段?
-
@Raghunandan 这是个好主意。我这样做了,发现自己遇到了更大的麻烦。当我在 MenuFragment 中时,我收到了 CartFragment 中声明的日志消息。这意味着,即使 Fragment 正在显示 Menu 的内容,它实际上也以某种方式在 Cart 片段中。为什么会这样? ;(
标签: android sqlite android-fragments