【问题标题】:How do I get all the rows from the table SQLite? [duplicate]如何从表 SQLite 中获取所有行? [复制]
【发布时间】:2016-05-12 14:50:19
【问题描述】:

大家好,我一直在尝试为我的大学开发一个 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

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

请帮帮我。我是新手。

【问题讨论】:

  • 那是一个不同的场景@ShreeKrishna.. 我无法从数据库中检索数据..

标签: java android sqlite arraylist


【解决方案1】:

不是while(cursor.isAfterLast()) 应该是while(!cursor.isAfterLast()) 或者干脆做

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

【讨论】:

  • 感谢@Shree Krishna 的工作! :-) 刚刚做到了cursor.moveToNext
【解决方案2】:
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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2019-09-06
    • 2015-02-16
    • 2019-09-20
    相关资源
    最近更新 更多