views:

92

answers:

2

Hi,

This has got me all confused! I'm trying to return the max value from a column in my database but the return value is always the name of the column.

The query I use:

private static final String SELECTMAX = "SELECT MAX(?) FROM " + TABLE_NAME ;

The (test) function to return the max value:

public int getMaxValue(String field){

   int r = 0;
   String f[] = new String[] {field};
   Cursor c = this.db.rawQuery(SELECTMAX, f);
   if (c.moveToFirst()) {
       String s = c.getString(0);
       Log.i("XXXXX","Max num: " + s); 
   }
   return r;
}

The column i'm querying is an INTEGER type but the result 's' is always the column name and not the desired value.

Thanks

+4  A: 

I don't have much experience in sqllite, is ? a parameter of a prepared statments? If so it looks like you are selecting the max of the string representation of your column name, you shouldn't pass the column name as a parameter.

So your query should look like.

SELECT MAX(s) FROM " + TABLE_NAME;

You are effectively executing

SELECT MAX('s') FROM " + TABLE_NAME;

Chris Diver
Yip, thats it! Thanks
Brett
+1 This is almost certainly it. If you want to conform Chris's answer you could change the code so that f is some other arbitrary string e.g. "Chris is right"
emory
No, this is definitely it. Why would I change f to an arbitrary string?
Brett
If you r sure it is right, there is no need to change it to an arbitrary string.
emory
+1  A: 

You should make use of the DatabaseUtils.stringForQuery() static method that is already in Android SDK to easily retrieve a value, this example is for String bot there is also method for Long

stringForQuery(SQLiteDatabase db, String query, String[] selectionArgs)

Utility method to run the query on the db and return the value in the first column of the first row.

Something like

String myString=DatabaseUtils.stringForQuery(getDB(),query,selectionArgs);
Pentium10
Thanks, hadn't come across that class yet. Looks like it could help a lot :)
Brett