【发布时间】:2021-01-03 21:51:40
【问题描述】:
所以,为了提供一点上下文,我目前正在开发一个带有数据库的应用程序。通过研究,很明显 Google 的 Room(使用 SQLite)是可行的方法。所以我已经完全设置了我的数据库,带有外键,还有@Transaction's(代表一对多或一对一的关系)。
目前,我一整天都在坚持某件事:
每当我尝试为实体(表)创建构造函数时,如果参数不是字符串,它会给我incompatible types: <null> cannot be converted to int 错误。 (或 float 或 double 等)。
我只是不知道为什么会这样,我也尝试删除所有外键并尝试使用尽可能少的代码,但它不起作用。
仅供参考:错误发生在生成的类中。此类是从您的 DAO 接口 (DatabaseAccessInterface) 生成的,您可以在其中列出所有查询函数,包括您的关系。生成的类比调用相关实体的构造函数:_tmpFan = new Fan(null,null,null,null,null,null,_tmpCreatedAt); 像这样,比说incompatible types: <null> cannot be converted to int
以前有没有人遇到过这个错误,或者你只需要坚持使用字符串? 如果您需要了解我的代码的一部分,只需询问,我会提供。 (如果要在一篇文章中全部发布,代码会非常多,但我会在下面发布一些片段)
接口内的事务/关系:
@Transaction
@Query("SELECT * FROM measurement_session WHERE fan_id = :fanID")
public List<FansWithMeasureSessions> getMeasureSessionsOfFan(int fanID);
粉丝班:
@Entity (tableName = "fan",
foreignKeys = {
@ForeignKey(entity = MeasurementSession.class,
parentColumns = "fan_id",
childColumns = "fan_id",
onDelete = ForeignKey.CASCADE)
},
indices = {
@Index(value = "customer_id", unique = true)
}
)
public class Fan {
@ColumnInfo(name = "customer_id")
public int customerID;
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "fan_id")
public int fanID;
@ColumnInfo(name = "fan_name")
public String fanName;
@ColumnInfo(name = "fan_type")
public String fanType;
@ColumnInfo(name = "diameter")
public float diameter;
@ColumnInfo(name = "length")
public float length;
@ColumnInfo(name = "width")
public float width;
@ColumnInfo(name = "created_at")
@TypeConverters(DateConverter.class)
public Date createdAt;
public Fan(int customerID, String fanName, String fanType, float diameter, float length, float width, Date createdAt) {
this.customerID = customerID;
this.fanName = fanName;
this.fanType = fanType;
this.diameter = diameter;
this.length = length;
this.width = width;
this.createdAt = createdAt;
}
}
FansWithMeasureSessions 类:
public class FansWithMeasureSessions {
@Embedded public Fan fan;
@Relation(
entity = MeasurementSession.class,
parentColumn = "fan_id",
entityColumn = "fan_id"
)
public List<MeasurementSession> measurementSessions;
}
注释掉了我的大部分其他代码,同时仍然保持错误,所以应该这样做!
【问题讨论】:
-
避免对 ID 使用不可为空的原始类型,因为它们需要能够保持“未设置”的值。使用
Integer而不是int。 -
我刚刚决定完全放弃构造函数,但这是一个很好的提示!谢谢
标签: java android sqlite android-studio android-room