public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
SQLiteDatabase myDatabase=this.openOrCreateDatabase("User",MODE_PRIVATE,null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS user(name VARCHAR,age INTEGER(2),id INTEGER PRIMARY KEY )");
myDatabase.execSQL("INSERT INTO user(name,age) VALUES('gaurav',20)");
myDatabase.execSQL("INSERT INTO user(name,age) VALUES('saurav',16)");
Cursor c=myDatabase.rawQuery("SELECT * FROM user",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", Integer.toString(c.getInt(ageIndex))); //tring to get this things in logs but instead it shows an error.
c.moveToNext();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
错误是
::E/ CursorWindow :无法从具有18行2列的CursorWindow读取第0行、第1列。
发布于 2018-06-25 05:13:22
尝试删除应用程序的数据并重新运行。
-1表示找不到列。该消息还指示只有2列,而不是3列(id,name和age),因此缺少一列(因此,age或name的-1 )。如果数据库存在,openOrCreate将打开数据库,因此不会应用对结构的任何更改(除非您执行了ALTER TABLE ADD COLUMN your_missing_column columntype
,因为它只会工作一次,所以您不想重复代码)。
此外,检查游标是否为null是无用的,请改用while(c.moveToNext()) { ...... }
并删除行c.moveToFirst();
(如果可以进行移动,则move方法返回true,否则返回false,因此可以使用while(c.moveToNext()) {....}
循环通过游标)。
封装在try/catch块中往往会混淆问题。所以我建议:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase myDatabase=this.openOrCreateDatabase("User",MODE_PRIVATE,null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS user(name VARCHAR,age INTEGER(2),id INTEGER PRIMARY KEY )");
myDatabase.execSQL("INSERT INTO user(name,age) VALUES('gaurav',20)");
myDatabase.execSQL("INSERT INTO user(name,age) VALUES('saurav',16)");
Cursor c=myDatabase.rawQuery("SELECT * FROM user",null);
int nameIndex=c.getColumnIndex("name");
int ageIndex=c.getColumnIndex("age");
while(c.moveToNext()) {
Log.i("Name",c.getString(nameIndex));
Log.i("Age", Integer.toString(c.getInt(ageIndex)));
}
}
https://stackoverflow.com/questions/51013804
复制相似问题