如何从SQLite表中获取所有行?

时间:2016-05-12 14:50:19

标签: java android sqlite arraylist

嘿伙计们,我一直在努力为我的大学开设一个Android项目,但我现在陷入困境。我想从表students中获取所有行,将其填充到ArrayList中,然后使用ListViewCardView来显示每个学生的记录。这是我正在使用的代码:

public ArrayList<String> getStudentsEntry()
    {

        ArrayList<String> arrayList = new ArrayList<>();

        Cursor cursor = db.query("STUDENT", ALL_COLUMN_NAME, null, null, null, null, null);
        if(cursor.getCount()<1) // UserName Not Exist
        {
            cursor.close();
            return null;
        }
        cursor.moveToFirst();
        while(cursor.isAfterLast()) {
            String name = cursor.getString(cursor.getColumnIndex("NAME"));
            String enrollment = cursor.getString(cursor.getColumnIndex("ENROLLMENT"));
            String year = cursor.getString(cursor.getColumnIndex("YEAR"));
            String dob = cursor.getString(cursor.getColumnIndex("DOB"));
            String email = cursor.getString(cursor.getColumnIndex("EMAIL"));
            String caste = cursor.getString(cursor.getColumnIndex("CASTE"));
            String fname = cursor.getString(cursor.getColumnIndex("FNAME"));
            String mname = cursor.getString(cursor.getColumnIndex("MNAME"));
            String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));
            String contact = cursor.getString(cursor.getColumnIndex("CONTACT"));

            arrayList.add(name);
            arrayList.add(enrollment);
            arrayList.add(year);
            arrayList.add(dob);
            arrayList.add(email);
            arrayList.add(caste);
            arrayList.add(fname);
            arrayList.add(mname);
            arrayList.add(address);
            arrayList.add(contact);

        }
        return arrayList;
    }

它没有返回任何内容。我无法从数据库中获取数据。数组大小为零:

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0

at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:25

请帮帮我们。我是这个人的新手。

2 个答案:

答案 0 :(得分:2)

它不是while(cursor.isAfterLast())它应该是while(!cursor.isAfterLast())或者只是做

while (cursor.moveToNext()) {
    ...
}

答案 1 :(得分:1)

ArrayList<String> arrayList = new ArrayList<>();

Cursor cursor = database.query("STUDENT", ALL_COLUMN_NAME, null, null, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
    cursor.close();
    return null;
}
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
    for (int column = 0; column < cursor.getColumnCount(); column ++) {
        arrayList.add(cursor.getString(column));    
    }
}
return arrayList;