我在尝试设置和写入对象的ArrayList时遇到空指针异常。根据互联网,最常见的原因是ArrayList永远不会被实例化,但即使我实例化它仍然会得到异常。见下面的代码。
public class Invoice {
private int invoiceNumber;
private Date date;
private int supplierCode;
private double total;
private ArrayList<InvoiceLines> lines;
private String status;
//getters and setters
public ArrayList<InvoiceLines> getLines() {
return this.lines;
}
public void setLines(ArrayList<InvoiceLines> lines) {
this.lines = lines;
}
public void addLine(int lineNumber, int qty, int productCode, int invoiceNumber) {
InvoiceLines il = new InvoiceLines();
il.setinvoiceNumber(invoiceNumber);
il.setlineNumber(lineNumber);
il.setqty(qty);
il.setproductCode(productCode);
il.setStatus("insert");
getLines().add(il);
}
// Servlet code
HttpSession session = request.getSession(false);
if(session==null) {
session = request.getSession(true);
Invoice invoice = new Invoice();
session.setAttribute("invoice", invoice);
ArrayList<InvoiceLines> lines = new ArrayList<InvoiceLines>();
session.setAttribute("lines", lines);
}
Invoice invoice = (Invoice) session.getAttribute("invoice");
session.setAttribute("invoice",invoice);
ArrayList<InvoiceLines> lines = (ArrayList<InvoiceLines>) session.getAttribute("lines");
session.setAttribute("lines ",lines);
// gets the data from the request
int qty = request.getParamater…;
int productCode = request.getParamater…;
int lineNumber = request.getParamater…;
int invoiceNumber = request.getParamater…;
if(request.getParameter("addLine")!=null) {
invoice.setLines(lines); ////// null pointer exception!!!
invoice.addLine(lineNumber, qty, productCode, invoiceNumber);
}
}
答案 0 :(得分:0)
NullPointerException
由invoice
null
引起,而不是与ArrayList
有关。
这可能是因为您有预先存在的会话。如果没有会话,您只需为会话分配新发票。
我建议如下:
if(session==null) {
session = request.getSession(true);
}
Invoice invoice = (Invoice) session.getAttribute("invoice");
if (invoice == null) {
invoice = new Invoice();
}
session.setAttribute("invoice", invoice);
// Similarly for lines.
我对会话并不熟悉,但我不清楚您是否总是需要再次设置属性值(如无条件调用session.setAttribute(...)
。您可能只能在创建新Invoice
时设置它。