我正在使用 SQLite 操作学习 android。以下代码导致 a CursorIndexOutOfBoundsException
,但我不知道为什么:
for (int i = 0; i < cursor.getCount(); i++) {
cursor.move(i);
String username = cursor.getString(1);
Log.i("username", username);
}
日志和异常:
09-13 12:39:18.317: INFO/row count:(3578): 10
09-13 12:39:18.317: INFO/username(3578): aaa_0
09-13 12:39:18.317: INFO/username(3578): aaa_1
09-13 12:39:18.317: INFO/username(3578): aaa_3
09-13 12:39:18.317: INFO/username(3578): aaa_6
09-13 12:39:18.337: ERROR/AndroidRuntime(3578): FATAL EXCEPTION: main
java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.example/com.example.MyActivity}:
android.database.CursorIndexOutOfBoundsException:
Index 10 requested, with a size of 10
您可以看到行数为 10,但在获取第 5 行时会引发异常。
完整的代码是:
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
public class MyActivity extends Activity {
private SQLiteDatabase db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createTables();
insertData();
queryData();
}
private void queryData() {
Cursor cursor = db.query("users", new String[]{"_id", "username", "password"}, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
Log.i("row count: ", "" + cursor.getCount());
for (int i = 0; i < cursor.getCount(); i++) {
cursor.move(i);
String username = cursor.getString(1);
Log.i("username", username);
}
}
}
private void insertData() {
for (int i = 0; i < 10; i++) {
String sql = "insert into users(username, password) values('aaa_" + i + "','123_" + i + "')";
db.execSQL(sql);
}
}
private void createTables() {
this.deleteDatabase("temp.db");
db = this.openOrCreateDatabase("temp.db", MODE_PRIVATE, null);
String sql = "create table users(_id integer primary key autoincrement, username text, password text)";
db.execSQL(sql);
}
}