为什么我只从SQLite查询中获取一行?

时间:2015-08-11 22:14:12

标签: android sqlite

我试图获取SQlite数据库的整个列,但我只得到一行。我的查询出了什么问题?

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;
    }

1 个答案:

答案 0 :(得分:2)

您正在循环Cursor行,但cursor.getString(i)返回当前光标位置的第i列的值

替换cursor.getString(i)
cursor.getString(cursor.getColumnIndex(YOUR_COLUMN_NAME))