首页 > 解决方案 > 获取房间实体中嵌入对象的空值

问题描述

我在一个 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;
    }
}

dao中查询数据库的列表查询如下:

@Query("SELECT * FROM specific_price_history WHERE code = :code ORDER BY date ASC")
    public abstract List<SpecificPriceHistory> listHistory(String code);

当我使用上述列表查询时,以下是我的观察结果:

我使用 adb 读取应用程序的实际数据库,并且数据库具有正确的值。此外,如果我将查询更改为仅从数据库中读取日期,则查询工作正常并返回日期。

我知道我在这里遗漏了一些非常愚蠢的东西,但我现在整天都在挠头!:(

标签: androiddatabaseandroid-room

解决方案


推荐阅读