无法选择表格中的第一行

时间:2015-03-15 15:10:38

标签: android sqlite

我有表主题,当我在adb shell中尝试查询时输出正常

SELECT * FROM subject;

输出是10行......

当我在Java / Android中做同样的事情时:

public ArrayList<Subject> getSubjectList() {
    SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();

    ArrayList<Subject> subjects = new ArrayList<Subject>();
    String selectQuery = "SELECT * FROM subject";
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        while (cursor.moveToNext()) {
            Subject subject = new Subject();
            subject.setId_subject(Integer.parseInt(cursor.getString(0)));
            subject.setName(cursor.getString(1));
            subjects.add(subject);
        }
    }

    cursor.close();

    DatabaseManager.getInstance().closeDatabase();

    return subjects;
}

输出为9行...不显示id为1的第一行,为什么?

2 个答案:

答案 0 :(得分:1)

因为您在移动第一个之后立即移至下一个moveToNext())行(moveToFirst())...

我通常做的是这样的事情:

        if (cursor != null)
        {
            if (cursor.moveToFirst())
            {
                do
                {
                    // ... 
                }
                while (cursor.moveToNext());
            }
        }

答案 1 :(得分:0)

因为在输入if语句时,moveToFirst(),然后在while循环的第一个条目中,您.moveToNext()。这意味着你跳过第一条记录。

所以改为使用do... while()构造:

if (cursor.moveToFirst()) {

    do {
        Subject subject = new Subject();
        subject.setId_subject(Integer.parseInt(cursor.getString(0)));
        subject.setName(cursor.getString(1));
        subjects.add(subject);
    }while (cursor.moveToNext())
}

参考:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html