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
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 ).
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With