SQLite不按日期排序

时间:2017-03-31 14:21:03

标签: android database sqlite

我需要选择表格中的所有元素,并根据有日期的列进行排序

这是表创建代码:

String query = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +" ( "+
            " id INTEGER PRIMARY KEY,"+
            " "+ COLUMN_LIST +" TEXT,"+
            " "+ COLUMN_PRICE + " TEXT,"+
            " "+ COLUMN_EXPIRY + " NUMERIC,"+
            " "+ COLUMN_DATE +" NUMERIC,"+
            " f_k INTEGER,"+
            " FOREIGN KEY(f_k) REFERENCES user(id)"+
            " ON DELETE CASCADE"+
            ")";

这是在我需要订购的列中插入元素的代码:

try{
    VAL.put( COLUMN_EXPIRY, String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );
}catch( ParseException e ){
    e.printStackTrace();
}

items.get( 2 ).toString()stringDate变量:

int day = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();

stringDate = Integer.toString( day ) +"-"+ Integer.toString( month ) +"-"+ Integer.toString( year );

select元素的代码:

final String QUERY = SELECT_ALL + t;
final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";
final Cursor RESULT = DB.rawQuery( QUERY + ORDER, null );

结果不满足我。日期不按顺序。
该列的某些元素也为空,我会使用另一列的不同顺序放下列表。
谢谢

3 个答案:

答案 0 :(得分:1)

" "+ COLUMN_EXPIRY +" NUMERIC,"

你存储

String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );

这是完全错误的,因为你得到的是String.valueOf(date)

您可以使用

" "+ COLUMN_DATE +" INTEGER,"

并获得以日期为单位的长值,该日期将转换为字符串

String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 )).getTime()) ) );

然后它应该工作

更新

别忘了改变

final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";

final String ORDER = " ORDER BY "+ COLUMN_EXPIRY +" DESC";

答案 1 :(得分:1)

为避免复杂查询,您可以尝试将日期元素存储在单独的字段中:

    " "+ COLUMN_EXPIRY_day + " NUMERIC,"+
    " "+ COLUMN_EXPIRY_month + " NUMERIC,"+
    " "+ COLUMN_EXPIRY_year + " NUMERIC,"+


您的查询的Order By子句:

ORDER BY COLUMN_EXPIRY_year, COLUMN_EXPIRY_month, COLUMN_EXPIRY_day

答案 2 :(得分:-2)

创建表格时, COLUMN_EXPIRY 的数据类型不正确,需要将其视为日期/时间。

如下所示更改它,你应该好好去:

...
" "+ COLUMN_EXPIRY + " DATETIME,"+
...