(Java) Android的Room数据库,通过date查询某一个月的数据,写好接口但似乎并没有返回数据,什么原因呢?

根据谷歌安卓开发者文档开发,使用了room+livedata+viewmodel+repository多个架构。

1.bean文件,存Date

    @ColumnInfo(name = "date")
    private Date date;

         public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

2.dao文件接口

@Query("SELECT * FROM Bill WHERE date BETWEEN :From AND :To ORDER BY id ASC")
    LiveData<List<Bill>> getBillsByMon(Date From,Date To);

3.room数据库不支持直接使用date,需要使用Converters

public class DateConverters {
    @TypeConverter
    public static Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }
}

4.billdatabase相关代码

@Database(entities = {Bill.class},version = 1,exportSchema = false)
@TypeConverters({DateConverters.class})
public abstract class BillRoomDatabase extends RoomDatabase {
    public abstract BillDao billDao();
}

5.问题主要在这里吧,activity中传了calendar,在repository转为date

        public LiveData<List<Bill>> getAllBillsByMonth(Calendar calendar) {
        Date dateFrom= Utils.ToMinDateInMonthByCal(calendar);
        Date dateTo= Utils.ToMaxDateInMonthByCal(calendar);
        LiveData<List<Bill>> mAllBillsByMonth = mbillDao.getBillsByMon(dateFrom, dateTo);
        return mAllBillsByMonth;
    }

utils方法代码,测试过应该对。

    //Cal-->date:当月最后一天
    public static Date ToMaxDateInMonthByCal(Calendar calendar){
        Date date = calendar.getTime();
        date.setMonth(date.getMonth() + 1);
        date.setDate(0);
        return date;
    }

    //Cal-->date:当月第一天
    public static Date ToMinDateInMonthByCal(Calendar calendar){
        Date date = calendar.getTime();
        date.setDate(1);
        return date;
    }

然后返回mAllBillsByMonth这个LiveData数据似乎为空,在recycler的adapter像返回全部数据那样调用,数据没有获取到,感觉是date的问题?

https://blog.csdn.net/w690333243/article/details/95906172