我在android应用程序中为数据库使用空间,并且在列出数据库中的对象时,未解析对象中的嵌入式字段,并导致null。
这是嵌入对象的定义。
public class Price {
@NonNull
private Double price;
@NonNull
private Date date;
public Price(Double price, Date date) {
Log.e("TEST3", "Asset price " + price + " " + date.toString());
this.price = price;
this.date = date;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
然后我正在使用一个抽象类,其中嵌入了上述对象。
public abstract class PriceHistory {
@NonNull
@Embedded
private Price price;
@NonNull
@TypeConverters(TimestampConverter.class)
@ColumnInfo(name = "last_updated_timestamp")
private Timestamp lastUpdatedTimestamp;
@Ignore
public PriceHistory(@NonNull Price price) {
this.price = price;
this.lastUpdatedTimestamp = DateTimeUtil.getCurrentTimestamp();
}
public PriceHistory(@NonNull Price price, @NonNull Timestamp lastUpdatedTimestamp) {
this.price = price;
this.lastUpdatedTimestamp = lastUpdatedTimestamp;
}
@NonNull
public Price getPrice() {
return price;
}
public void setPrice(@NonNull Price price) {
this.price = price;
}
@NonNull
public Timestamp getLastUpdatedTimestamp() {
return lastUpdatedTimestamp;
}
public void setLastUpdatedTimestamp(@NonNull Timestamp lastUpdatedTimestamp) {
this.lastUpdatedTimestamp = lastUpdatedTimestamp;
}
}
然后,我将上述类扩展为数据库所用的实际实体,如下所示
@Entity(tableName = "specific_price_history", primaryKeys = {"code", "date"})
public class SpecificPriceHistory extends PriceHistory {
@NonNull
private String code;
@Ignore
public SpecificPriceHistory(@NonNull String code, @NonNull Price price) {
super(price);
this.code = code;
}
public SpecificPriceHistory(@NonNull Price price, @NonNull Timestamp lastUpdatedTimestamp, @NonNull String code) {
super(price, lastUpdatedTimestamp);
if(price == null) {
Log.e("TEST2", "Still getting null");
}
this.code = code;
}
@NonNull
public String getCode() {
return code;
}
public void setCode(@NonNull String code) {
this.code = code;
}
}
查询岛中数据库的列表查询如下:
@Query("SELECT * FROM specific_price_history WHERE code = :code ORDER BY date ASC")
public abstract List<SpecificPriceHistory> listHistory(String code);
当我使用上述列表查询时,以下是我的观察结果:
我使用adb读取了我的应用程序的实际数据库,并且该数据库具有正确的值。另外,如果我将查询更改为仅从数据库中读取日期,则查询可以正常工作并返回日期。
我知道我在这里缺少一些非常愚蠢的东西,但是我整天都在挠头! :(