【问题标题】:Get data from current week and month in the Room Database从房间数据库中获取当前星期和月份的数据
【发布时间】:2019-04-07 17:19:17
【问题描述】:

我正在尝试从 Room 中的当前周和月获取数据。我创建了一个当前 Day 查询,它可以工作,但其他的都不能工作。

日查询(这个有效):

 @Query("SELECT * FROM expense_table WHERE day = strftime('%d', 'now')")
LiveData<List<Expense>> getExpensesDay();

周:

@Query("SELECT * FROM expense_table WHERE week = strftime('%W', 'now')")
LiveData<List<Expense>> getExpensesWeek();

月份:

@Query("SELECT * FROM expense_table WHERE month = strftime('%m', 'now')")
LiveData<List<Expense>> getExpensesMonth();

实体:

@Entity(tableName = "expense_table")
public class Expense  {

@PrimaryKey(autoGenerate = true)
private int expenseId;
private String note;
private Double value;
private String type;
private Long dateLong = System.currentTimeMillis();
private String date = new SimpleDateFormat("MM/yyyy").format(new Date(dateLong));
private static Calendar cal = Calendar.getInstance();
private int month = cal.get(Calendar.MONTH);
private int week = cal.get(Calendar.WEEK_OF_YEAR);
private int day = cal.get(Calendar.DAY_OF_MONTH);
private int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
private String weekDay = new DateFormatSymbols().getWeekdays()[dayOfWeek];

【问题讨论】:

    标签: android android-room


    【解决方案1】:

    根据文档,strftime('%W', ...) 用从 0 开始替换一年中的一周,Calendar.get(Calendar.WEEK_OF_YEAR) 从 1 开始返回一年中的一周。同样,strftime('%m', ...) 用基于 1 的值替换一年中的一周,Calendar.get(Calendar.MONTH) 用从 0 的值返回一年中的一周。

    所以,尝试替换 Entity 类中的字段计算:

    private int month = cal.get(Calendar.MONTH) + 1;
    private int week = cal.get(Calendar.WEEK_OF_YEAR) - 1;
    

    而不是

    private int month = cal.get(Calendar.MONTH);
    private int week = cal.get(Calendar.WEEK_OF_YEAR);
    

    【讨论】:

    • 这很奇怪,但是当我第一次尝试它时它不起作用,现在它可以工作了。也许我的查询有问题?我不知道。谢谢您的帮助。现在一切正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2021-03-26
    • 2021-12-01
    相关资源
    最近更新 更多