Search code examples
androidsqlitecursor

Integer stored as String returning wrong MAX value Sqlite Android


I've stored an Integer as a string in my Sqlite Database on Android but now I need to find the max value of the data. I have the following code:

    public String getMaxPageFromMainDB(){
    String maxNoStr =null;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT MAX(donebottombar) FROM customers",null);
    if(cursor.moveToFirst()) {
        maxNoStr = cursor.getString(0);
        cursor.moveToNext();
    }
    cursor.close();
    return maxNoStr;
}

When it comes to sorting the max value of numbers stored, 9 is coming before 11.

Is there anything wrong with my code or a way to better sort this without changing the database schema?

As answered below with a little change in code:

Cursor cursor = db.rawQuery("SELECT MAX(CAST(donebottombar AS INTEGER)) FROM customers",null);

Solution

  • When the stored data type is different from how you want to compare the values, you have to convert them:

    SELECT MAX(CAST(donebottombar AS INT )) FROM customers;
    SELECT MAX(CAST(donebottombar AS TEXT)) FROM customers;