12
votes

Here is a sample POJO

public class Product{
  private long id;
  private String name;
  private double price;

 ... constructor for all fields
 ... getters and setters
}

Now, in my productDAO if I have a query like this

@Query(select id, name from products)
LiveData<List<Product>> getProducts()

I get an error like:

The columns returned by the query does not have the fields [price] in ... Product even though they are annotated as non-null or primitive. Columns returned by the query: [id,name]

a) If I go in my Products and set

@Nullable
private double price;

the error remains.

b) If I go in my Products and set

@Ignore
private double price;

the error goes away but if I have another query for instance

 @Query(select p.id, p.name, p.price, t.someField from products p inner join table t)
    LiveData<List<Product>> getJoinQueryResponse()

because @Ignore is set the price is returned as 0.0.

So how to solve this? Hopefully I don't need to make a POJO for each different response from room...

1
have you properly annotated your Product class? You could explicitly set the @ ColumnInfo annotation. Also, I don't see @ Entity eitherZun
The Product Entity is defined in a separate file, the Pojo is used for Room query output handling. The Insert/Update will use the Entity format, but for the rest of the app I'll use the java POJO as it has many fields which are different from the entity. From my knowledge, the response fo @Query does not require an Entity class to output the result, just matching fields in itAlin
So you have a Product Entity, and a POJO Product? Why are you writing duplicate code? Why does the entity have different fields from the pojo?Zun
It looks duplicate but I have a few reasons for it. Imagine Products coming from a web service and having a different structure in json. To easy parse it, I still need a new POJO with similar structure. Then the web service structure changes, then change the POJO and not the entity. Not sure if it makes sense... I am still trying to figure out the best behavior.Alin

1 Answers

4
votes

Primitive types are by default not null. Make the price Double and this will solve the issue since it will be nullable then. Furthermore, you can add a custom getter to avoid having price as a null object.

public double getPrice(){
    if(this.price == null) return 0.0;
    return this.price;
}

@Ingore tells Room to ignore the field altogether, which is not what you want, based on your answer.