0

I'm creating a shopping cart using servlets. I've got a form in a .html file which send it to the post method of my servlet. Here's the form:

.HTML File
    <form action="Sess04" method="post">
        <label>
            Nazwa:
            <input type="text" name="name">
        </label><br>
        <label>
            Ilość:
            <input type="number" name="quantity" min="1">
        </label><br>
        <label>
            Cena:
            <input type="number" name="price" step="0.01" min="0">
        </label><br>
        <label>
            <input type="submit" value="Dodaj do koszyka">
        </label>
    </form>

Here's my servlet (doPost method, doGet is empty for now):

    HttpSession sess = request.getSession();
        List<Item> itemsList = (List<Item>) sess.getAttribute("cart");
        if (itemsList.isEmpty()) {                           ← Here NullPointException
            itemsList = new ArrayList<>();
        }
        String name = request.getParameter("name");
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        double price = Double.parseDouble(request.getParameter("price"));

        Item item = new Item(name, quantity, price);
        itemsList.add(item);
        sess.setAttribute("cart", itemsList);

        for (int i = 0; i <= itemsList.size(); i++) {
            response.getWriter().append("Product " + i + " - " + quantity + " x " + " " + price + "USD" + " = " + quantity*price + "USD");
        }

When I open the index in my browser, add the item and submit, it returns me the NullPointerException in the marked place (if). Why is that happening?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 2
    The list is `null` not empty if it doesn't exists. Basically your `isEmpty` check should be a `null` check. – M. Deinum Oct 29 '20 at 08:54

1 Answers1

1

The problem is here:

  List<Item> itemsList = (List<Item>) sess.getAttribute("cart");
    if (itemsList.isEmpty()) {                           ← Here NullPointException
        itemsList = new ArrayList<>();
    }

You don't want to check is the list is empty (it also would be useless to reinitialize an empty list), you want to check if itemList is null

 if (itemsList == null){                           
        itemsList = new ArrayList<>();
    }

By now you're calling isEmpty on null and this leads to the NullPointerExcetion

Esotopo21
  • 392
  • 1
  • 12