Search code examples
javaandroidsqliteandroid-cursor

Cursor to log id column value in activity


How do I loop to get id column values from users table, where "id" generated through :

id integer primary key autoincrement

I have records like this in my table:

id     name

1       Me

2      You

Here is what i think i should try:

public String[] getUsersId() {

    String selectQuery = "SELECT id FROM " + TABLE_USERS;
          SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery(selectQuery, null);
             String[] data = null;

    if (cursor.moveToFirst()) {
        do {

        } while (cursor.moveToNext());
    }

    db.close();
    return data;
}

Now, I would like to know how can I log all the "id" in my activity ?


Solution

  • Use cursor.getInt to get int value from Cursor:

    if (cursor.moveToFirst()) {
            do {
                 int id_row=cursor.getInt(cursor.getColumnIndex("id"));
                 //int id_row=cursor.getInt(0);
                 Log.d("TAG","id is ::"+id_row);
            } while (cursor.moveToNext());
        }