Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android and SQLite - retrieve max id from table

Tags:

android

sqlite

I am trying to create method to retrieve the max id from my table but I've problem.

This is my method. It's working, but return value is 0,

public int getLastId() {
    openDB();
    int id = 0;
    final String MY_QUERY = "SELECT MAX(_id) AS _id FROM organize";
    Cursor mCursor = mDb.rawQuery(MY_QUERY, null);  
    try {
          if (mCursor.getCount() > 0) {
            mCursor.moveToFirst();
            id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY));
          }
        } catch (Exception e) {
          System.out.println(e.getMessage());
        } finally {
            closeDB();
        }
return id;

}

can I fix this problem, thanks a lot

like image 713
user836807 Avatar asked Aug 15 '11 11:08

user836807


People also ask

How do I find the max ID in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

How would you retrieve data from SQLite table?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.

Does SQLite support limit?

Maximum Database SizeThe maximum size of a database file is 4294967294 pages. At the maximum page size of 65536 bytes, this translates into a maximum database size of approximately 1.4e+14 bytes (281 terabytes, or 256 tebibytes, or 281474 gigabytes or 256,000 gibibytes).


1 Answers

Rewrite this line

id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY));

to

id = mCursor.getInt(mCursor.getColumnIndex("_id"));  

or better to

id = mCursor.getInt(0);//there's only 1 column in cursor since you only get MAX, not dataset

And look at LogCat, it will tell you about your problem.

like image 143
ernazm Avatar answered Nov 08 '22 00:11

ernazm