ozioma ozioma - 1 year ago 65
Java Question

NullPointerException Exception when trying to get the value of a field in an Entity in Google App Engine

I have a Student Entity which has a field in it which is a reference to a Department Entity like this.

@Load private @Index Ref<Department> department;

Then the getter and setter for the Department field is shown below

public Department getDepartment() {
return department.get();

public void setDepartment(Key<Department> department) {
this.department = Ref.create(department);

The Student Entity also has a field in it which holds a reference to a SchoolFaculty Entity

private @Index Ref<SchoolFaculty> schoolFaculty;

It has the following getter and setter

public SchoolFaculty getSchoolFaculty() {
if (schoolFaculty != null)
return schoolFaculty.get();
return null;

public void setSchoolFaculty(Key<SchoolFaculty> schoolFaculty) {
this.schoolFaculty = Ref.create(schoolFaculty);

The Department Entity in turn has a field in it which holds a key to a Faculty Entity as shown below

private Key<SchoolFaculty> schoolFaculty;

the getter and setter for the field is shown below

public String getSchoolFaculty() {
return schoolFaculty.toWebSafeString();

public void setSchoolFaculty(Key<SchoolFaculty> schoolFaculty) {
this.schoolFaculty = schoolFaculty;

I have created a Department and SchoolFaculty Entity in the Local datastore using the google Api Explorer, the Department has its SchoolFaculty reference set to a valid value which is also present in the SchoolFaculty table, that is the Department has a faculty, but when I try to set the SchoolFaculty of a student using the following code I get a NullPointerException. Here is the code

student.setDepartment(Key.create(Department.class,student_programme.getDepartmentRef()));// student_programme is a reference to an Entity which I use to get the department and it works fine and the student gets its Department set to the Department Value.
if(student.getDepartment().getSchoolFaculty()) != null)

student.setSchoolFaculty(Key.create(SchoolFaculty.class,getDepartment().getSchoolFaculty()));// this is the line throws a null pointer Exception

I am using objectify for the datastore transaction and all reference to the objectify dependencies have been added.

Answer Source

because the student.getDepartment().getSchoolFaculty() is throwing null pointer before the condition statement is triggered, and google appengine key can not create a key for null entity or websafestring. So carefully debug and check if the getDepartment() is returning null or what it returns first, and if you want to create a null field of a key with data store using Key is to use the default e.g

Key.create(SchoolFaculty.class, "default"); // when it is null

hope this is useful

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download