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?
Android: Get highest value in column
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.
why we have to set sortOrder? –
Cilla
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;-).
I'm using ContentResolver.query(...). Is it possible there? What field to use? –
Mayonnaise
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;
}
© 2022 - 2024 — McMap. All rights reserved.
"MAX(COLUMN_NAME)"
should be used as the projection, not the selection. – Armillda