Search code examples
androidjsonrealmnullableprimitive

Realm: How can I set an int to nullable, so that if it gets the value "null" back from the json, it can be ignored


I have the following object:

@RealmClass
public class TripStop extends RealmObject implements Serializable {
@Nullable
private int arrival_time;
private String address;
@PrimaryKey
private int id;
@Nullable
private int departure_time;
private Destination place;
private CoordLocation location;

public int getArrival_time() {
    return arrival_time;
}

public void setArrival_time(int arrival_time) {
    this.arrival_time = arrival_time;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getDeparture_time() {
    return departure_time;
}

public void setDeparture_time(int departure_time) {
    this.departure_time = departure_time;
}

public Destination getPlace() {
    return place;
}

public void setPlace(Destination place) {
    this.place = place;
}

public CoordLocation getLocation() {
    return location;
}

public void setLocation(CoordLocation location) {
    this.location = location;
}
}

But everytime I get a json response back, with an int (or primitive) as null, I get an error in Realm that:

08-29 16:45:59.220: I/WSCalls(6370): error :Trying to set non-nullable field 'departure_time' to null.

I read that from Realm 3.5 it is possible to set null values, or set a default version, but I did not manage yet. How is that possible? I see that the @Nullable does not help


Solution

  • First of all:

    int is a primitive data type and cannot be assigend with null.

    Solution:

    You can change the type to Integer. An Integer can contain null, but it adds a little overhead because of boxing/unboxing. (see: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html)