Android持久性室:"无法弄清楚如何从游标中读取此字段"

And*_*oro 32 sqlite android android-room android-architecture-components

我正在尝试使用新的Android Persistence Room Library在两个数据库表之间创建关系.我查看了文档,并尝试实现https://developer.android.com/reference/android/arch/persistence/room/Relation.html上的示例:

 @Entity
 public class User {
 @PrimaryKey
     int id;
 }

 @Entity
 public class Pet {
     @PrimaryKey
     int id;
     int userId;
     String name;

 }

 @Dao
 public interface UserDao {
     @Query("SELECT * from User")
     public List<User> loadUser();
 }

 @Dao
 public interface PetDao {
     @Query("SELECT * from Pet")
     public List<Pet> loadUserAndPets();
 }


 public class UserAllPets {
     @Embedded
     public User user;
     @Relation(parentColumn = "user.id", entityColumn = "userId", entity = Pet.class)
     public List pets;
 }

 @Dao
 public interface UserPetDao {
     @Query("SELECT * from User")
     public List<UserAllPets> loadUserAndPets();
 }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

    ...error: Cannot figure out how to read this field from a cursor.
Run Code Online (Sandbox Code Playgroud)

和---关联:

 private java.util.List<?> pets;
Run Code Online (Sandbox Code Playgroud)

我想指出,我发现他们的文档中的一些内容确实令人困惑.例如缺少@PrimaryKeyUser缺少@Entity注释的事实,尽管它应该是一个实体(就像我看到的那样).有没有人遇到同样的问题?非常感谢提前

Dev*_*rim 140

文件真的很混乱.尝试使用以下课程:

1)用户实体:

@Entity
public class User {
    @PrimaryKey
    public int id; // User id
}
Run Code Online (Sandbox Code Playgroud)

2)宠物实体:

@Entity
public class Pet {
    @PrimaryKey
    public int id;     // Pet id
    public int userId; // User id
    public String name;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

3)UserWithPets POJO:

// Note: No annotation required at this class definition.
public class UserWithPets {
   @Embedded
   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; 
   */
}
Run Code Online (Sandbox Code Playgroud)
  • parentColumn是指嵌入式User表格的id列,
  • entityColumn指的是Pet表的userId(User- Pet关系)列,
  • entity指的是与表Pet有关系的table()User.

4)UserDao Dao:

@Dao
public interface UserDao {
    @Query("SELECT * FROM User")
    public List<UserWithPets> loadUsersWithPets();
}
Run Code Online (Sandbox Code Playgroud)

现在尝试loadUsersWithPets(),它返回用户的宠物列表.

编辑:看到我的其他答案很多很多关系.

  • @DevrimTuncer @AndreaSoro我们如何插入`UserWithPet`?文档说Room需要insert为`Entity`或它的集合/数组,所以我们不能直接插入`UserWithPet`. (14认同)
  • @AkshayChordiya我遇到了相同的错误-但:如果您使用LiveData更新您的UI,则只需编写两个不同的DAO(因此,对于Pet和User),然后只需将宠物插入pet- dao,将用户插入到user dao中,然后从User-Dao获得PetWithUserEntities。宠物也会出现。 (3认同)