Android: Get highest value in column
Asked Answered
M

3

5

I have an URL pointing to content and I need to get the highest value contained in one of the columns. Is there any aggregate function that will accomplish that or do I have to do this manually?

Mayonnaise answered 25/5, 2009 at 13:7 Comment(0)
M
19

If you're querying an Android content provider, you should be able to achieve this by passing MAX(COLUMN_NAME) in to the selection parameter of ContentResolver.query:

getContentResolver().query(uri, projection, "MAX(COLUMN_NAME)", null, sortOrder);

Where Uri is the address of the content provider. This should return the single row with the highest value in COLUMN_NAME.

Mccurdy answered 4/6, 2009 at 0:20 Comment(2)
"MAX(COLUMN_NAME)" should be used as the projection, not the selection.Armillda
why we have to set sortOrder?Cilla
C
1

Android's database uses SQLite, so SELECT MAX(thecolumn) FROM TheTable should work, just like in any other SQLite implementation (or for that matter any other SQL, "ite" or not;-). (If you're not using android.database you'd better specify what you're using instead;-).

Conceptacle answered 25/5, 2009 at 16:12 Comment(1)
I'm using ContentResolver.query(...). Is it possible there? What field to use?Mayonnaise
K
1

That worked for me.

Based on the responses of @Reto Meier and @Florian von Stosch.

public static long getMaxId(Context context) {

    long maxId = 0;

    Cursor maxCursor = context.getContentResolver().query(
            ProviderContentContract.CONTENT_URI,
            new String[]{"MAX(" + Table._ID + ")"},
            null,
            null,
            null);

    if (maxCursor != null && maxCursor.moveToFirst()) {
        maxId = maxCursor.getInt(0);
         maxCursor.close();
    }
    return maxId;
}
Kahlil answered 21/8, 2018 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.