I have 3 Fragments. (HOME,MENU,CART)
When user clicks on items in the MENU FRAGMENT, The clicked items go into a SQLite table(using the INSERT QUERY).
In the Cart Fragment, I use a select query to display the items user has chosen from the MENU FRAGMENT.
So, All this is happening.
PROBLEM:
- on MENU FRAGMENT: User clicks on items and adds them to cart (insertion done successfully)
- User goes on the CART FRAGEMENT. Updated values not shown in the CART FRAGMENT
- Now, If user goes to other fragments, and then comes back , The updated values are shown.
SNAPSHOT:
- User adds item 'Sada Uthappa' to the cart from the MENU FRAGMENT.
- User goes to the CART Fragment now, It shows empty.
- User goes to other fragments(like HOME,MENU) and then goes to CART Fragment. Voila. The updated result.
To get the updated data in the CART FRAGMENT, I have to click on the HOME fragment, then MENU fragment then CART fragment.
MENU FRAGMENT CODE:
Here is the code of the MENU Fragment: I call this method on Add to cart Button
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();
}
Here is the code onInsert() from DatabaseHelper class:
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;
}
CART FRAGMENT CODE:
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;
}