Search code examples
androidandroid-contentprovider

How to get complete row from ContentProvider with the bigest timestamp?


I have a database for messages:

message_id,
message_from,
message_to,
message_message,
message_time

If i select messages i do this for example:

public static List<MessageListEntry> selectMessages(Context context, String from, String to) {
    final String selection = DatabaseAdapter.COLUMN_MESSAGE_FROM + " = ? AND " + DatabaseAdapter.COLUMN_MESSAGE_TO + " = ?";
    final String[] selectionArgs = {from, to};

    final List<MessageListEntry> result = new ArrayList<>();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = ContentProvider.AVAILABLE;

    Cursor cursor = resolver.query(ContentProvider.CONTENT_URI, projection, selection, selectionArgs, null);

    if (cursor != null && cursor.moveToFirst()) {
        while (!cursor.isAfterLast()) {
            // create new object and add it to result list
        }

        cursor.close();

        return result;
    } else {
        if (cursor != null) {
            cursor.close();
        }

        return result;
    }
}

But what do i have to do if i only want to select the last message sent between from and to?


Solution

  • You have to sort by timestamp, and set the limit to just 1, like this:

    Cursor cursor = resolver.query(ContentProvider.CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            COLUMN_MESSAGE_TIME + " DESC LIMIT 1");