简体   繁体   中英

Append ArrayList<HashMap<String, String>> to another ArrayList<HashMap<String, String>>

I am using ArrayList<HashMap<String, String>> to store my cart items. Each time item is added to cart, item details are set to ArrayList and then calls setCart() method.

I want if items in ArrayList already exist then by calling setCart() it does not overwrite previous cart items.Instead it appends the ArrayList to the end of already existing ArrayList. I used ArrayList.add() method but it works only for HashMap<String,String> not working for ArrayList<HashMap<String, String>>

public class AddtoCart extends Application {
  ArrayList<HashMap<String, String>> cart;

  public void setCart(ArrayList<HashMap<String, String>> data) {
    cart = data;
  }

  public ArrayList<HashMap<String, String>> getCart() {
    return cart;
  }

  public int getSize() {
    return cart.size();
  }
}

Method called on addtocart button which is setting ArrayList in AddtoCart

private OnClickListener Cart = new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        cart = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map = new HashMap<String, String>();
            map.put(TAG_PID, pid);
            map.put(TAG_NAME, name);
            map.put(TAG_CATEGORY, category);
            map.put(TAG_PRICE, price);
            map.put(TAG_IMAGE,String.valueOf(resId));
            cart.add(map);

            AddtoCart obj = (AddtoCart) getApplicationContext();
            obj.setCart(cart);

        Intent a = new Intent("com.example.pb.VIEWCART");
        startActivity(a);
    }
};

}


I have suggestion for you.
We have to design the CartItem class instead of HashMap to enable the future changes easier. If you want to add any new tag related attributes at later stage, we can add these properties to CartItem class. It will help to achieve modular objects in you code.
Example:

public class CartItems
{

    int tagPid;
    String tagCategoy;
    int price
    String tagImage;

    // getters and setters methods of above attributes
}


public class AddtoCart extends Application {
ArrayList<CartItems> cart;

//remaining code
}

Update your method like this

public void setCart(ArrayList<HashMap<String, String>> data) {
    if(cart != null && cart.size() > 0)
        cart.addAll(data);
    else
        cart = data;
}

Or if you declare your ArrayList like this

ArrayList<HashMap<String, String>> cart = new ArrayList<HashMap<String, String>>();

You can remove the if-else condition and just do cart.addAll(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM