android - 从 Content Provider 获取当前日期数据

标签 android sqlite android-contentprovider android-cursorloader

我必须根据当前月份从 ContentProvider 获取数据。为了获取数据,我使用了以下查询:

SELECT * FROM Festivals
WHERE strftime('%Y-%m-%d',fest_date) >= date('now','-6 days') AND
strftime('%Y-%m-%d',fest_date)<=date('now') order by fest_date

我尝试在 CursorLoader 中编写相同的内容,如下所示:

new CursorLoader(this, FestivalContract.Festivals.CONTENT_URI, 
            PROJECTION, "strftime('%Y-%m-%d',fest_date)>=? AND strftime('%Y-%m-%d',fest_date)<=?", new String[] { "date('now','-6 days')", "date('now')" },
            FestivalContract.Festivals.FestivalColumns.FEST_NAME + " asc");

但是,它返回了所有记录。我找不到我的代码中的错误。

最佳答案

可能你在content provider中的查询方法是这样的:

SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        // check if the caller has requested a column which does not exists
        checkColumns(projection);
        // Set the table
        queryBuilder.setTables(MessageTable.TABLE_NAME);
        int uriType = uriMatcher.match(uri);
        switch (uriType) {
            case MESSAGES:
                break;

            case MESSAGE_ID:
                // adding the ID to the original query
                queryBuilder.appendWhere(MessageTable.COLUMN_ID + "=" + uri.getLastPathSegment());
                break;

            case BROADCAST_MESSAGES:
                groupBy = MessageTable.COLUMN_MESSAGE_ID;
                break;

            default:
                throw new IllegalArgumentException("Unknow URI: " + uri);

而如果您使用queryBuilder 则无法实现您的目标。 您有两个解决方法:

1- 以长格式将您的日期存储在数据库中。例如,您的节日日期是 unix 格式的日期,这意味着您应该将每个日期存储为数据库中的长数字。然后像这样在 cursorloader 中编写查询:

new CursorLoader(this, FestivalContract.Festivals.CONTENT_URI, 
        PROJECTION, "fest_date>=? AND fest_date<=?", new String[] { System.currentTimeMillis(), System.currentTimeMillis() - 6 * 24 * 3600 * 1000)", "" },
        FestivalContract.Festivals.FestivalColumns.FEST_NAME + " asc");

2- 第二种解决方案是自定义您的 ContentProvider 并为您要进行的这个特殊查询添加不同的 Content_Uri,然后在 query 您的提供商的方法检查您是否正在查询这个特殊的 uri,然后不要使用不允许您运行 sql 方法的 QueryBuilder,只需在内容中的数据库对象上执行您的查询字符串供应商,像这样:

return database.rawQuery(your_query_string_with_sql_methods, new String['your_params_or_whatever]);

关于android - 从 Content Provider 获取当前日期数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400186/

相关文章:

android - Activity-Alias 在应用更新时被移除

c# - 如何计算 C# 中 SQLite 阅读器返回的行数?

Android ContentProvider 光标问题

android - Content Observer 的 onChange 方法被多次触发

java - 如何一键对齐两个文本

android - achartengine Intent 不会启动

android - SQLite 错误 - 滥用聚合 : sum()

c# - Xamarin Forms 从 sqlite 数据库中删除

java - 从数组列表中获取值并保存

android - ClassCastException : android. 应用程序