get Max Id from SQLiteDatabase table - Android Database

Android examples for Database:Table Row Query

Description

get Max Id from SQLiteDatabase table

Demo Code


import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Main{
    /*from  www .  jav a 2 s  .  c  o m*/
    public static Long getMaxId(SQLiteDatabase db, String tableName,
            String columnName) {
        Cursor c = null;
        c = getCursor(db, tableName, null, "select max(" + columnName
                + ") ", null, null, null, null, null);
        try {
            if (c.moveToNext()) {
                return c.getLong(c.getColumnIndex(columnName));
            } else
                return null;
        } finally {
            if (c != null)
                c.close();
        }
    }
    
    public static Cursor getCursor(SQLiteDatabase db, String sqlString,
            String[] selectionArgs) {
        return db.rawQuery(sqlString, selectionArgs);
    }
    public static Cursor getCursor(SQLiteDatabase db, String table,
            String[] columns, String selection, String[] selectionArgs,
            String groupBy, String having, String orderBy, String limit) {
        Cursor cursor = db.query(table, columns, selection, selectionArgs,
                groupBy, having, orderBy, limit);
        return cursor;
    }
}

Related Tutorials