应用程序在从SQLite数据库访问数据后崩溃,安卓。

huangapple go评论105阅读模式
英文:

App crashes after accessing data from SQLite Database android

问题

在我的代码中,我正在创建一个SQLite数据库和一个表,并将数据添加到表中,这部分工作正常。但是问题出现在访问数据时。它检索存储的数据,最后导致应用程序崩溃。是 while 循环引起了这个问题吗?

以下是我的代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 创建一个新的数据库或访问现有数据库
        SQLiteDatabase myDatabase = this.openOrCreateDatabase("Users", MODE_PRIVATE, null);

        // 如果表不存在,则创建一个表
        myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users(name VARCHAR,age INT(3))");

        // 将数据插入到用户表中
        // 单行值
        myDatabase.execSQL("INSERT INTO users(name,age) VALUES('Robert',28)");
        // 多行值
        myDatabase.execSQL("INSERT INTO users(name,age) VALUES('Derek',30), ('Israel',31), ('Jared',24)");

        // 访问数据并遍历用户表
        Cursor c = myDatabase.rawQuery("SELECT * FROM users", null);

        int nameIndex = c.getColumnIndex("name");   // 为姓名列设置索引
        int ageIndex = c.getColumnIndex("age");     // 为年龄列设置索引

        c.moveToFirst(); // 将光标设置在起始位置

        // 逐行遍历表格
        while (c != null){
            Log.i("name", c.getString(nameIndex));
            Log.i("age", c.getString(ageIndex));

            c.moveToNext();
        }
    }
}

以下是日志:

2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Robert
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 28
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Derek
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 30
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Israel
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 31
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Jared
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 24
2020-10-26 13:29:53.200 18545-18545/com.example.databasedemo1 D/AndroidRuntime: Shutting down VM
2020-10-26 13:29:53.206 18545-18545/com.example.databasedemo1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.databasedemo1, PID: 18545
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.databasedemo1/com.example.databasedemo1.MainActivity}: 

android.database.CursorIndexOutOfBoundsException: Index 4 requested, with a size of 4
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: android.database.CursorIndexOutOfBoundsException: Index 4 requested, with a size of 4
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at com.example.databasedemo1.MainActivity.onCreate(MainActivity.java:39)
        at android.app.Activity.performCreate(Activity.java:6975)
英文:

In my code, I am creating a SQLite database and a table, and adding the data into the table, this part is working fine. But the problem arises when I'm accessing the data. It retrieves the stored data and at the end crashes the app. Does the while loop cause this?

Here's my code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //creating  a new Or accessing an existing database
        SQLiteDatabase myDatabase = this.openOrCreateDatabase("Users",MODE_PRIVATE,null);

        //creating a table if it does not exist
        myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users(name VARCHAR,age INT(3))");

        //inserting data into the users table
        //single row of values
        myDatabase.execSQL("INSERT INTO users(name,age) VALUES('Robert',28)");
        //multiple rows of values
        myDatabase.execSQL("INSERT INTO users(name,age) VALUES('Derek',30), ('Israel',31), ('Jared',24)");

        //accessing data and traversing across table users
        Cursor c = myDatabase.rawQuery("SELECT * FROM users",null);

        int nameIndex = c.getColumnIndex("name");   //setting index  for name column
        int ageIndex = c.getColumnIndex("age");     //setting index  for age column

        c.moveToFirst(); //setting the cursor on starting position

//traversing across the table row by row
        while (c != null){
            Log.i("name",c.getString(nameIndex));
            Log.i("age",c.getString(ageIndex));

            c.moveToNext();
        }

    }
} 

Here are the logs:

2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Robert
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 28
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Derek
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 30
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Israel
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 31
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/name: Jared
2020-10-26 13:29:53.199 18545-18545/com.example.databasedemo1 I/age: 24
2020-10-26 13:29:53.200 18545-18545/com.example.databasedemo1 D/AndroidRuntime: Shutting down VM
2020-10-26 13:29:53.206 18545-18545/com.example.databasedemo1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.databasedemo1, PID: 18545
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.databasedemo1/com.example.databasedemo1.MainActivity}: 

android.database.CursorIndexOutOfBoundsException: Index 4 requested, with a size of 4
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: android.database.CursorIndexOutOfBoundsException: Index 4 requested, with a size of 4
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at com.example.databasedemo1.MainActivity.onCreate(MainActivity.java:39)
        at android.app.Activity.performCreate(Activity.java:6975)

答案1

得分: 1

循环遍历 Cursor 行的方式是错误的。<br/> 删除第一次调用的 c.moveToFirst();,并使用 c.moveToNext() 来检查 Cursor 中是否还有另一行:

while (c.moveToNext()) {
    Log.i("name", c.getString(nameIndex));
    Log.i("age", c.getString(ageIndex));
}

这样,循环将在访问最后一行后停止,因为 c.moveToNext() 将返回 false

英文:

The way that you loop through the rows of the Cursor is wrong.<br/>
Remove the 1st call to c.moveToFirst(); and use c.moveToNext() to check if there is another row in the Cursor:

while (c.moveToNext()) {
    Log.i(&quot;name&quot;,c.getString(nameIndex));
    Log.i(&quot;age&quot;,c.getString(ageIndex));
}

This way the loop will stop after the last row is accessed because c.moveToNext() will return false.

huangapple
  • 本文由 发表于 2020年10月26日 17:04:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64534124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定