JAVAlang.NullPointerException?将get方法指定给arraylist时
您好,我正在尝试显示从另一个类添加到“表”类的客户订单
public class PaymentScreenController {
public ArrayList<Customer> allcustomers; // Defining allcustomers Arraylist
public Table tbl; // Creating instance of Table class
@FXML
public void initialize() {
allcustomers = tbl.getCustomers(); // Error seems to come from here when i assign allcustomers to the getcustomers method of table
System.out.println(tbl.getCustomers());
System.out.println("test");
for (Customer customer : allcustomers) {
System.out.println(customer.getCustomerorder());
}
}
}
任何帮助都将不胜感激,谢谢
**更多代码*
public void submitorder(ActionEvent actionEvent) throws IOException {
//create a new UNIQUE customer to store that customers menu items
Customer cust = new Customer();
//add items to customer
cust.getCustomerorder().addAll(order);
// Adds the customer order to the table class
tbl.getCustomers().add(cust);
System.out.println(tbl.getCustomers());
//clear menu choices screen
lvOrder.getItems().clear();
// Once added the desired number of customers move to next screen
//extra customer was being added as a customer was put into the ArrayLust after the check happened.
if (tbl.getCustomers().size() == noOfDiners) {
Window mainWindow = btnSubmitOrder.getScene().getWindow();
Parent newRoot = FXMLLoader.load(getClass().getResource("payment_screen.fxml"));
mainWindow.getScene().setRoot(newRoot);
}
}
因此,客户向他们的订单中添加内容,然后客户被添加到表类中
# 1 楼答案
如果NPE在你的评论中提到的那句话中提出,这意味着, 当调用方法
initialize()
时,变量tbl
不会被实例化并保持null
值当你调用
tbl.getCustomers()
时,它会导致NullPointerException,因为tbl
在这里是空的我没有看到任何代码,创建表的对象并将其分配给变量。也许它发生在这个类之外的某个地方,因为你的变量有
public
修饰符,那么请确保这个代码调用的时间早于initialize
方法你需要创建一个
Table
的对象,比如:要获得更具体的答案,请在这里分享你的堆栈跟踪
# 2 楼答案
在这里,您只是声明了表,而不是创建它的实例
要做到这一点,你必须做
tbl = new Table(insert arguments here);
这就是为什么你有一个空指针