I have an array of integers which I'm trying to loop through, then get a product object by ID based on the array. I am then trying to add the created product object to another array but this is giving me a null pointer exception error.
Code for adding object to array:
ArrayList<Integer> cartIds = new ArrayList<Integer>();
void viewCart(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
ProductDAO productDAO = new ProductDAO();
ArrayList<Product> cartArrayList = null;
for(int i = 0; i< cartIds.size(); i++){
Product product = productDAO.getProductByIdCart(cartIds.get(i));
Product cartProduct = new Product(product.getId(), product.getMake(), product.getModel(), product.getEngine(), product.getPower(), product.getSpeed(),
product.getCategory(), product.getYear(), product.getPrice());
cartArrayList.add(cartProduct);
}
request.getSession(true).setAttribute(IConstants.SESSION_KEY_CART, cartArrayList);
System.out.println(cartArrayList);
RequestDispatcher rd = request.getRequestDispatcher("/shop-main.jsp");
rd.forward(request, response);
}
My DAO:
public Product getProductByIdCart(int id) {
DBManager dmbgr = new DBManager();
Connection con = dmbgr.getConnection();
int carId = 0;
String make = null;
String model = null;
String engine = null;
String power = null;
String speed = null;
String category = null;
String year = null;
String price = null;
String location = null;
Product carData = new Product();
String query = "SELECT * FROM PRODUCTDATA WHERE PRODUCT_ID = "+ id +"";
try {
PreparedStatement stmt = con.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
carId = (rs.getInt(1));
make = (rs.getString(2));
model = (rs.getString(3));
engine = (rs.getString(4));
power = (rs.getString(5));
speed = (rs.getString(6));
category = (rs.getString(7));
year = (rs.getString(8));
price = (rs.getString(9));
location = (rs.getString(10));
Product tempCar = new Product();
tempCar.setId(carId);
tempCar.setMake(make);
tempCar.setModel(model);
tempCar.setEngine(engine);
tempCar.setPower(power);
tempCar.setSpeed(speed);
tempCar.setCategory(category);
tempCar.setYear(year);
tempCar.setPrice(price);
tempCar.setImg_location(location);
carData = tempCar;
System.out.println(tempCar);
}
} catch (SQLException e) {
e.printStackTrace();
}
return carData;
}
And my product constructor:
public Product(int id, String make, String model, String engine, String power, String speed, String category, String year, String price){
this.id = id;
this.make = make;
this.model = model;
this.engine = engine;
this.power = power;
this.speed = speed;
this.category = category;
this.year = year;
this.price = price;
}