Bắt lỗi not null trong If vẫn bị lỗi

em đã bắt chỗ if not null Customer nhưng khi nó null lại báo lỗi Nullpoint

List<SurveyTestUser> listTestUser=getEntityManager().createQuery("from SurveyTestUser survey where survey.surveyTest.testId="+instance.getTestId()).getResultList();
if(listTestUser!=null){
	for (SurveyTestUser surveyTestUser : listTestUser) {
		if(surveyTestUser.getUserId().getUserId()!=null){
			listUsersSelected.add(getEntityManager().find(TblUsers.class, surveyTestUser.getUserId().getUserId()));
		}
		if(surveyTestUser.getCustomer().getCustomerId()!=null){
			listCustomerSelected.add(getEntityManager().find(Customers.class, surveyTestUser.getCustomer().getCustomerId()));	
		}
	}
}

kiểm tra chỗ này có null không

2 Likes

nó có thể null ạ… nên em bắt nếu not null thì listCustomerSelect mới add thêm

nó có thể null thì em thêm như này mới đúng chứ

2 Likes

ô em cảm ơn ạ… vừa nãy e có thử nhưng em lại viết

if (  surveyTestUser.getCustomer().getCustomerId() != null && surveyTestUser.getCustomer() != null)

lại không được

1 Like

Để tránh NullPointerException (Con trỏ rỗng) thì đảm bảo đối tượng không rỗng trước khi gọi những phương thức của đối tượng đó.

Bạn làm ngược rồi đấy.
Đúng ra phải là:

if (surveyTestUser.getCustomer() != null && surveyTestUser.getCustomer().getCustomerId()  != null)

Kiểm tra getCustomer() trước, sau đó mới kiểm tra getCustomerId(). Thằng trước (getCustomer()) không rỗng thì mới gọi các phương thức của nó được chứ.

1 Like

dạ vâng… e cảm ơn ạ… cần ghi nhớ

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?