How to sort a cursor based on a time string

青春壹個敷衍的年華 提交于 2019-12-12 04:36:53

问题


My question if fairly simple, I have this segment of code

Cursor mCursor = this.getContentResolver().query(
            PlayerContentProviderDB.CONTENT_URI, fulldataColumns, null, null,
            Players.SCORE +" ASC");

This code, from everything I've seen, should be sorting the cursor in ascending order based on Players.SCORE but it is not.

For reference Players.SCORE will always be a string in the format
mm:ss:msmsms ( read minute:second:millisecond).

Also here is the code for the query method in my ContentProvider

public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    checkColumns(projection);
    queryBuilder.setTables(PlayerContract.Players.PLAYERS_TABLE_NAME);
    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
    case ALL_SCORES:
    break;
    case SCORE_ID:
    queryBuilder.appendWhere(PlayerContract.Players.ID + "="
    + uri.getLastPathSegment());
    break;
    default:
    throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    SQLiteDatabase db = this.dbHelper.getReadableDatabase(); 
    Cursor cursor = queryBuilder.query(db, projection, selection,
    selectionArgs, null, null, sortOrder);
    // Notify potential listeners
    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;

My question is why dose this code not work and how can I fix it?

(Another interesting note about this code is that I am also trying to add a limit statement to the end of the sort, which I have read works, however mine is not)


回答1:


If I am reading the SQLite documentation correctly, date() expects a value of the form %Y-%m-%d. Yours is not.

If you are using two-digit minute and second values, this should sort without any function.

(above was from original question, not the update)

Also, you are querying a ContentProvider. There is no requirement that a ContentProvider offer sorting. If this is your own ContentProvider, you need to check on its side whether or not it is passing the sort clause on to SQLite or whatever your backing store is.




回答2:


I finally found the answer to this question. As it turns out my code was correct, however for some reason that I am still working on my ContentProvider.query() was being called twice. Once with the correct parameters and again with incorrect parameters.(i.e: sortOrder == null).

Also note that you can not sort a string of numbers in numerical order as sql sorts ints and strings differently



来源:https://stackoverflow.com/questions/26576141/how-to-sort-a-cursor-based-on-a-time-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!