clue11
clue11

Reputation: 147

Why am I only getting one row from SQLite query?

I'm trying to get the entire column of a SQlite database, but I am only getting one row. What is wrong with my query?

String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_EMAIL + " TEXT UNIQUE," + KEY_GROUP + " TEXT," +
                KEY_UID + " TEXT," + KEY_CREATED_AT + " TEXT" + ")";

public ArrayList<String> getGroupNames() {
        ArrayList<String> groupNames = new ArrayList<>();

        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT " + KEY_GROUP + " FROM " + TABLE_LOGIN;

        Cursor cursor = db.rawQuery(selectQuery, null);
        System.out.println("The cursor had this many rows: " + cursor.getCount());

        if (cursor != null && cursor.getCount() != 0) {
            System.out.println("Putting all group names into arraylist");
            cursor.moveToFirst();

            while(!cursor.isAfterLast()) {
                System.out.println(cursor.getColumnIndex(KEY_GROUP));
                groupNames.add(cursor.getString(cursor.getColumnIndex(KEY_GROUP)));
                cursor.moveToNext();

            }
        }
        System.out.println(groupNames);
        return groupNames;
    }

Upvotes: 0

Views: 66

Answers (1)

sadegh saati
sadegh saati

Reputation: 1170

You are looping on Cursor rows but cursor.getString(i) returns the value of ith columns of current cursor position

replace cursor.getString(i) with

cursor.getString(cursor.getColumnIndex(YOUR_COLUMN_NAME))

Upvotes: 2

Related Questions