Android Persistence room:“无法弄清楚如何从游标读取此字段" [英] Android Persistence room: "Cannot figure out how to read this field from a cursor"

查看:366
本文介绍了Android Persistence room:“无法弄清楚如何从游标读取此字段"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a relation between two database tables using the new Android Persistence Room Library. I looked at the documentation and tried to implement the example found at 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();
 }

我收到以下错误

    ...error: Cannot figure out how to read this field from a cursor.

关于:

 private java.util.List<?> pets;

我想指出的是,我在他们的文档中发现了一些令人困惑的地方.例如,缺少@PrimaryKey以及User类缺少@Entity批注的事实,尽管它应该是一个实体(如我所见,它很受欢迎).有人遇到过同样的问题吗?提前谢谢

I would like to point out that I found some things in their docs really confusing. For example the lack of @PrimaryKey and also the fact that the User class is missing the @Entity annotation, although it's supposed to be an entity (as fas as I see it). Did anybody run into the same problem? Thanks a lot in advance

推荐答案

Document is really confusing. Try with just below classes:

1)用户实体:

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

2)宠物实体:

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

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; 
   */
}

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆