ashwin mahajan
ashwin mahajan

Reputation: 1782

Android : How to update listview item?

I have a ListView which contains a list of products. Each list item contains a TextView which shows the quantity in the cart, if the product is in the cart.

The cart is a popup and the product quantity can be changed from the cart.

The issue is when I dismiss the cart pop up, the quantity in the list item view is not updated since the getView is not called.

I am aware of PopupWindow.OnDismissListener but dont know how to update the view explicitly or call getView forcibly.

Is there a way I can achieve this? Thank you.

Upvotes: 0

Views: 2691

Answers (2)

Ait Bri
Ait Bri

Reputation: 587

If you are passing the list of PRODUCT objects via BaseAdapter constructor, You can get the position of the item whose cart is clicked by getChildAt(position). If the cart quantity is changed, based upon above position you can trace the item in ArrayList as well. So pass the new value at particular product at arraylist and call notifyDataSetChanged(). This will update your listview

If possible,I recommend to update ListView to use RecyclerView, It is more flexible than ListView.

Upvotes: 0

Reaz Murshed
Reaz Murshed

Reputation: 24211

So from your question I guess, you're passing a ArrayList of Product in your adapter. So lets just assume the Product class looks like this.

class Product {
    public String productName; 
    public int quantity;
}

Now when you update the quantity from the cart, you need to update the ArrayList which you have passed to the adapter and then call notifyDataSetChanged() on the adapter to see the changes in the list.

So I'm writing some pseudo code for changing the quantity from the cart.

public void changeQuantity(int index, boolean quantityIncreased) {
    if(quantityIncreased) products.get(index).quantity = products.get(index).quantity + 1;
    else  products.get(index).quantity = products.get(index).quantity - 1;
}

Now Override your PopupWindow.OnDismissListener like this. Call notifyDataSetChanged to see the effect in your list.

@Override
public void onDismissListener() {
    adapter.notifyDataSetChanged();
}

Upvotes: 2

Related Questions