Android Persistence room: “Cannot figure out how to read this field from a cursor”

Document is really confusing. Try with just below classes:

1) User Entity:

public class User {
    public int id; // User id

2) Pet Entity:

public class Pet {
    public int id;     // Pet id
    public int userId; // User id
    public String name;

enter image description here

3) UserWithPets POJO:

// Note: No annotation required at this class definition.
public class UserWithPets {
   public User user;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
   public List<Pet> pets; // or use simply 'List pets;'

   /* Alternatively you can use projection to fetch a specific column (i.e. only name of the pets) from related Pet table. You can uncomment and try below;

   @Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class, projection = "name")
   public List<String> pets; 
  • parentColumn refers to Embedded User table’s id column,
  • entityColumn refers to Pet table’s userId (UserPet relation) column,
  • entity refers to table(Pet) which has relation with User table.

4) UserDao Dao:

public interface UserDao {
    @Query("SELECT * FROM User")
    public List<UserWithPets> loadUsersWithPets();

Now try loadUsersWithPets(), which returns the users with their list of pets.

Edit: See my other answer for many ot many relation.

Leave a Comment