首页 > 解决方案 > 插入列表在房间 Db 中给出错误

问题描述

我从 API 获取字符串列表,当我尝试在 Room Db 中插入时,我收到一个错误 -

Type of the parameter must be a class annotated with @Entity or a collection/array of it.

这是我的方法

 @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(list: List<String>).        --> this method giving error

这是它的桌子

@Entity(tableName = "insuree")
public class Insuree {
    @ColumnInfo(name = "insurerName")
    @NonNull
    public String insurerName;

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "_id")
    public int id;
}

我该如何解决这个错误,或者有没有其他方法可以让这个东西工作。

标签: androidandroid-room

解决方案


@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(list: List<String>).        --> this method giving error

在这种情况下,Room 无法确定要将数据插入到哪个表中。

也就是说,当使用@Insert注释时,Room 根据要插入的对象的类确定要插入的表,然后仅当使用@Entity定义类时(以便它是注册到 Room 的类型/由 Room 理解)。然后可以从类/实体中确定构建底层代码时要使用的实际表名。

因此,您似乎应该拥有:-

fun insertAll(list: List<Insuree>) 

或者也许更合适

fun insertAll(insurees: List<Insuree>)

然后,您需要从您的 String 数组中创建一个 Insuree 对象列表,例如

    String[] insureeStringList = new String[]{"Insurer1","Insurer2","Insurer3"}; //<<<<< The list of Insurer names
    ArrayList<Insuree> insurees = new ArrayList<>();
    Insuree i = new Insuree();
    for (String insuree: insureeStringList) {
        i.insurerName = insuree;
        insurees.add(i);
    }
    // insurees is a List of Insuree objects
    appDatabase.insureeDao().insertAll(insurees);

推荐阅读