-1

I am using an object list which is a list of another object I get this error when I set an object to this object list

Logcat error

java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference

List cart item class

public class ListCartItem {
    public List<CartItem>cartItems;
}

Cart item class

public class CartItem {
    public String id;
    public String count;
    public String price;
    public String nameAR;
    public String nameEN;
    public String imageSet;
}

Main activity

CartItem cartItem=new CartItem();
cartItem.id= String.valueOf(ids.get(position));
cartItem.count= String.valueOf(count.get(position));
cartItem.imageSet=image.get(position);
cartItem.nameAR=name_ar.get(position);
cartItem.nameEN=names_en.get(position);
cartItem.price=price.get(position);

ListCartItem listCartItem=new ListCartItem();
listCartItem.cartItems.add(cartItem);
Mohamed Shaheen
  • 610
  • 8
  • 21
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Mark Jan 05 '19 at 17:08
  • you need to initialise cartItems – Ashvin solanki Jan 05 '19 at 17:10
  • The real question is: why would you create a class that only returns a list of `CartItem` instead of you doing this:: `List listCartItems = new ArrayList<>();` ? Then you just add the `CartItem` Like `listCartItems.add(cartItem)` – Barns Jan 05 '19 at 17:23

1 Answers1

1

Inside ListCartItem class you don't allocate the memory (initialize object) for your List<CartItem>cartItems; Possible solution is:

public class ListCartItem {
    public List<CartItem> cartItems;
    public ListCartItem() {
        cartItems = new ArrayList<>();
    }
}
Dmytro Ivanov
  • 1,260
  • 1
  • 8
  • 10