android - 插入列表在房间 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;
}
我该如何解决这个错误,或者有没有其他方法可以让这个东西工作。
解决方案
@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);
推荐阅读
- python - Discord.py 反应计数不说话
- .htaccess - 如何在 htaccess 中重写 url 以隐藏子文件夹?
- react-native - React Native ,Flatlist :如何删除“未读”笔记,一旦你点击
- r - sym 参数类型无效
- node.js - 如何从 JSON Nodejs 获取数据?
- django - Nest.js 序列化器,如 Django
- python - Pandas Series:ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
- vue.js - 在子函数上使用父道具
- spring-boot - 如何处理 Spring Boot 2.4.5 中的错误页面?
- entity-framework - Entity Framework Core 多对多解决歧义