CurSorIndexOutOfBoundSexception:请求索引2,大小为2。如何解决?

发布于 2025-01-31 17:35:18 字数 729 浏览 2 评论 0原文

查询SQLite数据库时,仅显示2行。是否可以解决此错误?

Cursor cursor = database.rawQuery("SELECT * FROM Category", null);
            cursor.moveToFirst();
            for (int i = 0; i < 10; i++) {
                categoryList.add(new Category(cursor.getInt(0), cursor.getString(1)));
                cursor.moveToNext();
            }
            cursor.close();
            database.close();

错误:

Process: com.triangle.learningenglish, PID: 30477
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.triangle.learningenglish/com.triangle.learningenglish.Select.SelectCategory}: android.database.CursorIndexOutOfBoundsException: Index 2 requested, with a size of 2

When querying the SQLite database, only 2 lines are displayed. Is it possible to fix this error?

Cursor cursor = database.rawQuery("SELECT * FROM Category", null);
            cursor.moveToFirst();
            for (int i = 0; i < 10; i++) {
                categoryList.add(new Category(cursor.getInt(0), cursor.getString(1)));
                cursor.moveToNext();
            }
            cursor.close();
            database.close();

Error:

Process: com.triangle.learningenglish, PID: 30477
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.triangle.learningenglish/com.triangle.learningenglish.Select.SelectCategory}: android.database.CursorIndexOutOfBoundsException: Index 2 requested, with a size of 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

假情假意假温柔 2025-02-07 17:35:18

该错误的原因是您没有检查光标是empity。您只需循环循环循环并检索可能具有或没有价值的结果。
我想这条代码解决了您的问题

Cursor cursor = database.rawQuery("SELECT * FROM Category", null);
            
int numberOfRows = cursor.getCount();
int counter = 1;
cursor.moveToFirst();
        while(numberOfRows !=0 && counter <= numberOfRows){
             categoryList.add(new Category(cursor.getInt(0), cursor.getString(1)));
             counter++;
             cursor.moveToNext();
            }
            cursor.close();
            database.close();

the reason for that error is you are not checking that if a cursor is empity. you just simply cycle over the for loop and retrieving the result which may have or have not a value.
i guess this line of code solves your problem

Cursor cursor = database.rawQuery("SELECT * FROM Category", null);
            
int numberOfRows = cursor.getCount();
int counter = 1;
cursor.moveToFirst();
        while(numberOfRows !=0 && counter <= numberOfRows){
             categoryList.add(new Category(cursor.getInt(0), cursor.getString(1)));
             counter++;
             cursor.moveToNext();
            }
            cursor.close();
            database.close();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文