Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android and SQLite - retrieve max id of a table

Tags:

android

sqlite

I am trying to create a method to retrieve the max id of a specific table.

This is the code that doesn't work:

private long getMaxId()
{
    String query = "SELECT MAX(id) AS max_id FROM mytable";
    Cursor cursor = db.rawQuery(query, new String[] {"max_id"});

    int id = 0;     
    if (cursor.moveToFirst())
    {
        do
        {           
            id = cursor.getInt(0);                  
        } while(cursor.moveToNext());           
    }
    return id;
}

The exception being thrown is this:

E/AndroidRuntime(24624): android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x200408

I suppose the problem is this line:

            id = cursor.getInt(0); 

Does anybody have an idea of how to fix this?

Thanks.

like image 733
Dan Avatar asked Nov 29 '10 10:11

Dan


1 Answers

Try replacing:

Cursor cursor = db.rawQuery(query, new String[] {"max_id"});

with

Cursor cursor = db.rawQuery(query, null);

From the rawQuery description , for the 2nd argument:

You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.

Since you dont have any placeholders in your SQL query, maybe it is the source of the problem.

like image 133
ccheneson Avatar answered Oct 14 '22 12:10

ccheneson