Showing the number of quantity when press + button and decrease - button - android

I wanted to show the number of quantities and price where price = (single item price * the total number of quantities). I understand how to show the items but I'm struggling with how to put buttons for each item and displaying their quantity. How to add + and - for each row and on click on the button calculate the price respectively. My concept is like a shopping cart but it shows the quantity and the + and - buttons and the price.
public class myAdapter extends RecyclerView.Adapter<myAdapter.MyViewHolder> {
String data1[],data2[];
int images [];
Context context;
public myAdapter(Context ct, String s1 [], String s2[], int img[] ){
context = ct;
data1 = s1;
data2 = s2;
images = img;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.mytext1.setText(data1[position]);
holder.mytext2.setText(data2[position]);
holder.myimage.setImageResource(images[position]);
}
#Override
public int getItemCount() {
return images.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mytext1, mytext2 , quantity;
ImageView myimage , plus , minus;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mytext1 = itemView.findViewById(R.id.Nama_Pakej);
mytext2 = itemView.findViewById(R.id.Harga);
quantity = itemView.findViewById(R.id.quantity);
myimage = itemView.findViewById(R.id.imageView);
plus = itemView.findViewById(R.id.tambah);
minus = itemView.findViewById(R.id.tolak);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (itemView == plus){
}
}
}
}
This is my adapter. I'm using card view to display my items.

To achieve "price = (single item price * the total number of quantities)" use a simple method -
public double mul(double quantity, double price) {
return quantity * price;
}
Then use increment and decrement and update the quantity and total price . example- here single item price 100 .
private int increment;
private int decrement;
private String totalprice;
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO
//Increment
increment = Integer.parseInt(quantity.getText().toString());
increment++;
quantity. setText(String. valueOf(increment));
//update price
totalprice = String.valueOf(mul(increment, 100));
mytext2.setText(totalprice);
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO
//Decrement
decrement = Integer.parseInt(quantity.getText().toString());
decrement--;
quantity. setText(String. valueOf(decrement));
//update price
totalprice = String.valueOf(mul(decrement, 100));
mytext2.setText(totalprice);
}
});
You can check also my answer to avoid losing data while activity lifecycle changes .

Related

Checkbox changing state when scrolling in recyclerview

I made a small app that shows me a list of all the apps installed to my phone I want to add a check box to every cardview so that I can mark my favorite apps and other classification. The problem is when scrolling through the list the state of the checkbox change ex. I checked chrome and when I scrolled down then scrolled up chrome is not marked and a random app is checked. I searched for other question related to this problem but none of those solutions worked for me.
updated version of appsadapter.java
public class AppsAdapter extends RecyclerView.Adapter<AppsAdapter.ViewHolder>{
private final SparseBooleanArray array=new SparseBooleanArray();
public class ViewHolder extends RecyclerView.ViewHolder{
public CardView cardView;
public ImageView imageView;
public TextView textView_App_Name;
public CheckBox checkBox;
public ViewHolder (View view){
super(view);
checkBox = (CheckBox) view.findViewById(R.id.chckbox);
cardView = (CardView) view.findViewById(R.id.card_view);
imageView = (ImageView) view.findViewById(R.id.imageview);
textView_App_Name = (TextView) view.findViewById(R.id.Apk_Name);
//textView_App_Package_Name = (TextView) view.findViewById(R.id.Apk_Package_Name);
}
}
private Context context1;
private List<String> stringList;
public AppsAdapter(Context context, List<String> list){
context1 = context;
stringList = list;
}
//viewholder initialized
#Override
public AppsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view2 = LayoutInflater.from(context1).inflate(R.layout.cardview_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(view2);
return viewHolder;
}
//DATA IS BOUND TO VIEWS
private SparseBooleanArray sba = new SparseBooleanArray();
#Override
public void onBindViewHolder(ViewHolder viewHolder,final int position){
viewHolder.setIsRecyclable(false);
ApkInfoExtractor apkInfoExtractor = new ApkInfoExtractor(context1);
final String ApplicationPackageName = (String) stringList.get(position);
//calling apps name and icon
String ApplicationLabelName = apkInfoExtractor.GetAppName(ApplicationPackageName);
Drawable drawable = apkInfoExtractor.getAppIconByPackageName(ApplicationPackageName);
//setting app name and icon for every card
viewHolder.textView_App_Name.setText(ApplicationLabelName);
viewHolder.imageView.setImageDrawable(drawable);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sba.put(position, !sba.get(position));
notifyDataSetChanged();
}
});
viewHolder.checkBox.setChecked(sba.get(position));
/*Adding click listener on CardView to open clicked application directly from here
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = context1.getPackageManager().getLaunchIntentForPackage(ApplicationPackageName);
if(intent != null){
context1.startActivity(intent);
}
else {
Toast.makeText(context1,ApplicationPackageName + " Error, Please Try Again.", Toast.LENGTH_LONG).show();
}
}
});*/
}
#Override
public int getItemCount(){
return stringList.size();
}
}
That is because in the recycler view, item views are re used to show new data. You have to add a variable in your data item that holds the state of the checkbox at a particular position. Then in the onBindViewHolder you can check the value of the tracking variable and set the state of the checkbox like yourCheckbox.setchecked(item.getSelected()) set the tracking variable value in the onCheckChanged method
set view onclicklistener in BindViewholder method so you can use the current position of item as in
private SparseBooleanArray sba = new SparseBooleanArray();
#Override
public void onBindViewHolder(ViewHolder viewHolder,final int position){
viewHolder.setIsRecyclable(false);
ApkInfoExtractor apkInfoExtractor = new ApkInfoExtractor(context1);
final String ApplicationPackageName = (String) stringList.get(position);
//calling apps name and icon
String ApplicationLabelName = apkInfoExtractor.GetAppName(ApplicationPackageName);
Drawable drawable = apkInfoExtractor.getAppIconByPackageName(ApplicationPackageName);
//setting app name and icon for every card
viewHolder.textView_App_Name.setText(ApplicationLabelName);
viewHolder.imageView.setImageDrawable(drawable);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sba.put(position,!sba.get(position));
notifyDataSetChanged();
}
});
viewHolder.checkBox.setChecked(sba.get(position));
}
Set checkbox inside checkBox onclickListener
holder.mCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
mDataModel = (DataModel) checkBox.getTag();
mDataModel.setChecked(checkBox.isChecked());
arrayList.get(position).setChecked(checkBox.isChecked());
}
});

OnClick for item in RecyclerView

I am witnessing a wierd behavior of RecyclerView. so I have set an OnClickListener in the ViewHolder on a Button which is meant to do 3 things, when the user clicks:
Add the current item's data to an ArrayList [displayed on a different Fragment]
Display a Toast to the user.
modify the UI of the selected item. [i.e setVisibility of Button to View.INVISIBLE etc..]
now, while the first two tasks of the OnClickListener are fulfilled successfully and apply only to the selected item, the third one which is meant to modify the UI of the selected item only, instead gets also applied to each 9th Item on the RecyclerView.
How do I prevent this behavior?
Why is this behavior occurring with the 3rd task only?
i.e from previous answers on this. particular topic that I saw, I got the notion that it's better to insert the OnClickListener in the ViewHolder rather then putting it in onBindViewHolder, which did not solve the issue. I have followed other suggestions on stackOverflow and all failed.
Here is my code:
static class ItemsRecyclerAdapter extends RecyclerView.Adapter<ItemsRecyclerAdapter.ItemsViewHolder>{
FragmentActivity fragmentActivity;
List<ProductItem> data;
LayoutInflater inflater;
private int id;
private int shopCode;
public ItemsRecyclerAdapter(List<ProductItem> data, FragmentActivity fragmentActivity, int id, int shopCode) {
this.fragmentActivity = fragmentActivity;
this.data = data;
this.inflater = LayoutInflater.from(fragmentActivity);
this.id = id;
this.shopCode = shopCode;
}
#Override
public ItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.pricing_item, parent, false);
return new ItemsViewHolder(v);
}
#Override
public void onBindViewHolder(final ItemsViewHolder holder, int position) {
ProductItem itemPrice = data.get(position);
holder.productName.setText(itemPrice.getProductName());
holder.quantity.setText(itemPrice.getProductQuantity());
holder.tvPrice.setText(itemPrice.getproductPrice());
Picasso.with(fragmentActivity).load(itemPrice.getThumbUrl()).into(holder.imgProduct);
}
#Override
public int getItemCount() {
return data.size();
}
class ItemsViewHolder extends RecyclerView.ViewHolder{
TextView productName, quantity, tvPrice;
ImageView imgProduct;
Button btnAddToBasket, btnAdd, btnRemove;
Typeface myCustomFont = Typeface.createFromAsset(fragmentActivity.getAssets(), "fonts/Assistant-SemiBold.ttf");
public ItemsViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
quantity = (TextView) itemView.findViewById(R.id.manufacturer);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
imgProduct = (ImageView) itemView.findViewById(R.id.imgProduct);
btnAddToBasket = (Button) itemView.findViewById(R.id.btnAddToBasket);
btnAdd = itemView.findViewById(R.id.btnAdd);
btnRemove = itemView.findViewById(R.id.btnRemove);
btnAdd.setVisibility(View.INVISIBLE);
btnRemove.setVisibility(View.INVISIBLE);
quantity.setTypeface(myCustomFont);
productName.setTypeface(myCustomFont);
tvPrice.setTypeface(myCustomFont);
Typeface fontAwesomeBasketIcon = Typeface.createFromAsset(fragmentActivity.getAssets(), "fontawesome-webfont.ttf");
btnAddToBasket.setTypeface(fontAwesomeBasketIcon);
btnAdd.setTypeface(fontAwesomeBasketIcon);
btnRemove.setTypeface(fontAwesomeBasketIcon);
btnAddToBasket.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
MyBasketFragment.myBasketList
.add(new ProductItem(data.get(pos).getProductName(), data.get(pos).getProductQuantity(),
data.get(pos).getproductPrice(), data.get(pos).getThumbUrl(), id, shopCode));
btnAddToBasket.setOnClickListener(null);
Toast.makeText(fragmentActivity, "New product..", Toast.LENGTH_SHORT).show();
btnAdd.setVisibility(View.VISIBLE);
btnRemove.setVisibility(View.VISIBLE);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ItemsFragment.atomic.incrementAndGet();
btnAddToBasket.setText(String.valueOf(atomic.get()));
}
});
}
}
}
On every Click of an item, I assign a boolean in the instantiated object to true and and then I run notifyDataSetChanged() which. updates all items with data objects which have a boolean true. this way I'm ensuring that only the selected object will be updated.
It looks something like this:
ViewHolder
class ItemsViewHolder extends RecyclerView.ViewHolder {
TextView productName, quantity, tvPrice;
ImageView imgProduct;
Button btnAddToBasket, btnAdd, btnRemove;
Typeface myCustomFont = Typeface.createFromAsset(fragmentActivity.getAssets(), "fonts/Assistant-SemiBold.ttf");
public ItemsViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
quantity = (TextView) itemView.findViewById(R.id.manufacturer);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
imgProduct = (ImageView) itemView.findViewById(R.id.imgProduct);
btnAddToBasket = (Button) itemView.findViewById(R.id.btnAddToBasket);
btnAdd = itemView.findViewById(R.id.btnAdd);
btnRemove = itemView.findViewById(R.id.btnRemove);
btnAdd.setVisibility(View.INVISIBLE);
btnRemove.setVisibility(View.INVISIBLE);
quantity.setTypeface(myCustomFont);
productName.setTypeface(myCustomFont);
tvPrice.setTypeface(myCustomFont);
Typeface fontAwesomeBasketIcon = Typeface.createFromAsset(fragmentActivity.getAssets(), "fontawesome-webfont.ttf");
btnAddToBasket.setTypeface(fontAwesomeBasketIcon);
btnAdd.setTypeface(fontAwesomeBasketIcon);
btnRemove.setTypeface(fontAwesomeBasketIcon);
}
public void bind(final ProductItem item) {
btnAddToBasket.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
item.clicked = true;
item.atomic.incrementAndGet();
Toast.makeText(fragmentActivity, "New product..", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
MyBasketFragment.myBasketList
.add(new ProductItem(item.getProductName(), item.getProductQuantity(),
item.getproductPrice(), item.getThumbUrl(), id, shopCode));
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ItemsFragment.atomic.incrementAndGet();
btnAddToBasket.setText(String.valueOf(atomic.get()));
}
});
}
}
onBindViewHolder
#Override
public void onBindViewHolder(final ItemsViewHolder holder, final int position) {
ProductItem itemPrice = data.get(position);
holder.productName.setText(itemPrice.getProductName());
holder.quantity.setText(itemPrice.getProductQuantity());
holder.tvPrice.setText(itemPrice.getproductPrice());
Picasso.with(fragmentActivity).load(itemPrice.getThumbUrl()).into(holder.imgProduct);
holder.bind(itemPrice);
if(itemPrice.clicked){
holder.btnAddToBasket.setOnClickListener(null);
holder.btnAddToBasket.setText(String.valueOf(atomic.get()));
holder.btnAdd.setVisibility(View.VISIBLE);
holder.btnRemove.setVisibility(View.VISIBLE);
} else {
holder.btnAddToBasket.setText("\uf291");
holder.btnAdd.setVisibility(View.INVISIBLE);
holder.btnRemove.setVisibility(View.INVISIBLE);
}
}
I think getAdapterPosition() is causing the problem. Please, try creating a new int attribute position in the viewholder, onBindViewHolder pass the the position to the viewholder, holder.position = position, and in your viewholder use the position, so will be int pos = position instead of getAdapterPosition()

How to sum cardView item values in recyclerView and display the total sum on a textView outside the recyclerView

I am working on restaurant app wants to display selected items for order, with their price per item and total price (count*price) of each item. I want to add those total price of list of card items and display on text view outside Recycler View that will change dynamically.
Inside each card View, there are two buttons(- and +) that change the count value for each item so that it changes the total price of each item.
Here is My adapter class
public class MyListsToOrderAdapter extends
RecyclerView.Adapter<MyListsToOrderAdapter.MyHOldd>{
ArrayList<Element> element;
Context ctx;
TextView textView;
String c;
String db = "Elements";
String dbp = "Prices";
PriceDao priceDao;
ElementDao elementDao;
int count=0;
private LayoutInflater inflater;
float v1,v4,v5,v2,v3,v6;
float x1,x2,x3=0;
public MyListsToOrderAdapter( ArrayList<Element> element,Context ctx,TextView textView) {
this.textView=textView;
this.ctx = ctx;
this.element = element;
inflater = LayoutInflater.from(ctx);
}
#Override
public MyListsToOrderAdapter.MyHOldd onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_lists_to_order,parent,false);
MyHOldd holder = new MyHOldd(view,ctx,element);
return holder;
}
#Override
public void onBindViewHolder(final MyListsToOrderAdapter.MyHOldd holder, final int position) {
priceDao=setUpDBPrice();
String bs= element.get(position).getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bs)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v1 = Float.parseFloat(pricev);
v2= Float.parseFloat(element.get(position).getCount());
v3=v1*v2;
final String res = String.valueOf(v3);
holder.listName.setText(element.get(position).getDescription());
holder.add.setImageResource(R.drawable.add);
holder.sub.setImageResource(R.drawable.minus);
holder.pricess.setText(pricev);
holder.totalPriceT.setText(res);
holder.status.setText(element.get(position).getCount());
if(v5==1)v5=v6;
else if(v5==2) v5=-v6;
else if(v5==3) v5=0;
else v5=v3;
v4=v4+v5;
String ch = String.valueOf(v4);
textView.setText("Total: "+ch);
}
#Override
public int getItemCount() {
return element.size();
}
class MyHOldd extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView listName;
public TextView pricess;
public TextView status;
public TextView totalPriceT;
public ImageView add;
public ImageView sub;
int count;
Context ctx;
ArrayList<Element> element = new ArrayList<>();
ElementDao elementDao = setupDbElement();
public MyHOldd(View itemView, Context ctx, ArrayList<Element> element) {
super(itemView);
this.ctx=ctx;
this.element=element;
listName = (TextView)itemView.findViewById(R.id.TitemName);
pricess = (TextView)itemView.findViewById(R.id.TitemPrice);
status = (TextView)itemView.findViewById(R.id.Tstatus);
totalPriceT = (TextView)itemView.findViewById(R.id.totalPrice);
add = (ImageView) itemView.findViewById(R.id.TplusSign);
sub = (ImageView) itemView.findViewById(R.id.TminusSign);
add.setOnClickListener(this);
sub.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Element element = this.element.get(position);
String bd= element.getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bd)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v6 = Float.parseFloat(pricev);
x3=v6*count;
v5=0;
count= Integer.parseInt(element.getCount());
if(view.getId()==add.getId()) {
count = count+1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=1;
} else if (view.getId()==sub.getId()) {
if(count==0) {
count = 0;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=3;
}
else {
count = count-1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=2;
}
}
count= Integer.parseInt(element.getCount());
}
}
#Habatamu
Everytime you click add or sub imageview the textview for totalSum should be updated. In your case, the override method onclick does not seems to be updating the totalSum.
it works like this for me, I changed notifyDataSetChanged(); into notifyItemChanged(position);
so that I can get the total value (v4) and pass it to text view as shown
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Element element = this.element.get(position);
String bd= element.getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bd)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v6 = Float.parseFloat(pricev);
x3=v6*count;
v5=0;
count= Integer.parseInt(element.getCount());
if(view.getId()==add.getId()) {
count = count+1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=1;
} else if (view.getId()==sub.getId()) {
if(count==0) {
count = 0;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=3;
}
else {
count = count-1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=2;
}
}
count= Integer.parseInt(element.getCount());
}
}
///////////////////////////////
so that I can get the total value (v4) and pass it to text view as shown
#Override
public void onBindViewHolder(final MyListsToOrderAdapter.MyHOldd holder, final int position) {
priceDao=setUpDBPrice();
String bs= element.get(position).getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bs)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v1 = Float.parseFloat(pricev);
v2= Float.parseFloat(element.get(position).getCount());
v3=v1*v2;
final String res = String.valueOf(v3);
holder.listName.setText(element.get(position).getDescription());
holder.add.setImageResource(R.drawable.add);
holder.sub.setImageResource(R.drawable.minus);
holder.pricess.setText(pricev);
holder.totalPriceT.setText(res);
holder.status.setText(element.get(position).getCount());
holder.addNote.setText("Add");
// Calculating the Total price of all items
if(v5==1)v5=v6;
else if(v5==3) v5=-v6;
else if(v5==2) v5=0;
else v5=v3;
v4=v4+v5;
// displayin on the textView
String ch = String.valueOf(v4);
textView.setText("Total: "+ch);
}

remove elements from listview in android

i have 2 arrays productname and price. my each row in listview contains productname,price and an image button remove. when i click remove button,the selected productname and price should be removed from my array as well as from my listview. Please guide me doing this,is very important for me. If there is another way of doing this plz let me know.i m student only!
this is my CartActivity
public class CartActivity extends Activity implements View.OnClickListener {
CartAdapter contactAdapter;
ListView listView;
public String productname[]=new String[10];
public String price[]=new String[10];
int i=0,m;
CartActivity(String scanContent){
this.content = scanContent;
}
public CartActivity() {}
String product,Price;
String pri,prod;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.cart_list_view);
contactAdapter = new CartAdapter(this,R.layout.activity_cart_list_view);
listView.setAdapter(contactAdapter);
intent = getIntent();
productname = intent.getStringArrayExtra("productname");
price = intent.getStringArrayExtra("price");
for(int j=0;j<price.length;j++) {
product = productname[j];
Price = price[j];
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
contactAdapter.add(contacts);
}
}
}
this is my CartAdapter
public class CartAdapter extends ArrayAdapter {
List list = new ArrayList();
int ind,x=0;
public CartAdapter(CartActivity context, int resource) {
super(context, resource);
}
public void add(Cart object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_cart_list_view,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_name =(TextView) row.findViewById(R.id.product_name);
contactHolder.tx_price =(TextView) row.findViewById(R.id.price);
contactHolder.cancelButton = (ImageButton) row.findViewById(R.id.cancel_button);
row.setTag(contactHolder);
}
else
{
contactHolder = (ContactHolder)row.getTag();
}
cancelButton.setTag(position);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
list.remove(index.intValue());
notifyDataSetChanged();
}
});
Cart contacts = (Cart) this.getItem(position);
contactHolder.tx_name.setText(contacts.getItemname());
contactHolder.tx_price.setText(contacts.getPrice());
return row;
}
static class ContactHolder
{
TextView tx_name,tx_price;
ImageButton cancelButton;
}
}
this is my Cart
public class Cart {
private String itemname,price;
public Cart(String itemname,String price) {
this.setItemname(itemname);
this.setPrice(price);
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setPrice(String price) {
this.price = price;
}
public String getItemname() {
return itemname;
}
public String getPrice() {
return price;
}
}
my each row in a listview contains this
Just do this,
in your adapter class,
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.remove(position); //position is getView position
// above line will remove from arraylist
notifyDataSetChanged(); //this line reflects change in listview
}
});
To remove from Activity class,
better create an ArrayList first.
ArrayList<Cart> cardList = new ArrayList<Cart>();
add into arrayList,
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
cardList.add(contacts);
contactAdapter.add(contacts); // this line should be removed if you work with arrayList
}
now create a method to remove from ActivityCard arrayList,
//call this method from cancelimage click in adapter class
public void removeFromList(int position){
cardList.remove(position); //this will remove from activity arraylist
}
At the end calculate your bill from existing cartList data.
*** You can also create adapter class object with cardList just changing your constructor. If you do this then just call removeFromList on cancelimage click and put,
adapter.notifyDataSetChanged();
after
cardList.remove(position);
it will refresh your listview also.

Increment and Decrement a quantity within a RecyclerView

I have a problem. If I click on an increase button, the item quantity also increases. When I click on the decrement button, I get the same result. Here is where I declare the ArrayList<>:
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
public static Context c;
int quantity=0;
public static int qty,cty,mty=0,qty1;
public static int sendcost;
public static String curry;
MyHolder holder;
public ArrayList<Integer> quantity1 = new ArrayList<Integer>();
private List<Spacecraft> spacecrafts = new ArrayList<>();
CustomButtonListener customButtonListener;
private boolean mShowQuantity;
public MyAdapter(Context c, ArrayList<Spacecraft> spacecrafts, boolean showQuantity ) {//ArrayList<ShoppingCartEntry> showQuantity , boolean showQuantity
MyAdapter.c = c;
this.spacecrafts = spacecrafts;
this.mShowQuantity = showQuantity;
for(int i =0; i< spacecrafts.size();i++ )
{
quantity1.add(0);
//quantity[i]=0;
}
}
This is where I organise the RecyclerView:
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(final MyHolder holder, final int position) {
final Spacecraft s = spacecrafts.get(position);
holder.nameTxt.setText(s.getName());
PicassoClient.downloadImage(c, s.getImageUrl(), holder.img);
holder.propellentTxt.setText(s.getPropellant());
holder.descTxt.setText(s.getDescription());
holder.carbohydratesTxt.setText(s.getCarbohydrates());
holder.fatcontentTxt.setText(s.getFatcontent());
holder.minaralsTxt.setText(s.getMinarals());
holder.costTxt.setText("" + s.getCost());
holder.rateTxt.getText().toString();
try{
holder.rateTxt.setText(quantity1.get(position)+"");
}catch(Exception e){
e.printStackTrace();
}
MyHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity = Integer.parseInt(holder.rateTxt.getText().toString());
cty = Integer.parseInt(holder.costTxt.getText().toString());
curry =holder.nameTxt.getText().toString();
qty1 = 1;
quantity = quantity + 1;
holder.rateTxt.setText(String.valueOf(quantity));//quantity
sendcost = quantity * cty;//single item cost
mty = mty + cty * qty1;// Total Cost
MainActivity.Totalcost.setText("Total cost :" + String.valueOf(mty));
ShoppingCartHelper.setQuantity(s, quantity);
}
});
Here is my decrease button:
MyHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
qty1=1;
quantity = Integer.parseInt(holder.rateTxt.getText().toString());
cty = Integer.parseInt(holder.costTxt.getText().toString());
if(quantity == 0)
{
}
else
{
quantity = quantity - 1;
holder.rateTxt.setText(String.valueOf(quantity));
mty =mty - cty*qty1;
MainActivity.Totalcost.setText("Total cost :" + String.valueOf(mty));
ShoppingCartHelper.setQuantity(s, quantity);
}
}
});
holder.quan.setVisibility(View.GONE);
return;
}
#Override
public int getItemCount() {
return spacecrafts.size();
}
}
Any suggestions on how to make the decrease button work?
Based on the information in the comments, they are all accurate. You need to update the ArrayList<> each time you increase and decrease the quantities. After you do that, you need to notify your RecyclerViews adapter like so:
quantity1.set(position, quantity);
notifyDataSetChanged();
When you update the ArrayList<>, any new changes that were made would appear in the RecyclerView.

Categories

Resources