我试图从名为 Train_list
的数据库中检索一些数据,当我尝试这样做时,我遇到了错误:
D/Final Error: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
经过一番谷歌搜索和一些线索和错误后,我意识到游标返回了一个 null
值,所以我质疑数据是否实际上被插入到数据库中。所以我使用了第三方插件(或者你想怎么调用它)来查看数据是否确实存在于数据库中
正如您所看到的,数据库确实有三个条目。现在,当我尝试使用以下代码读取数据库时:
setContentView(R.layout.activity_display_data);
Bundle bundle = getIntent().getExtras();
no_name = (ListView) findViewById(R.id.Disp_list);
String message = bundle.getString("package");
String parameter;
SQLiteDatabase db = openOrCreateDatabase(message, SQLiteDatabase.CREATE_IF_NECESSARY, null);
SQLiteDatabase db1 = openOrCreateDatabase("Train_list.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor header;
namer=(TextView)findViewById(R.id.T1);
try {
header = db1.rawQuery("Select Train_name From Train_list Where Train_no='"+message.substring(0,(message.length()-3))+ "'", null);
header.moveToFirst();
String temp = header.getString((header.getColumnIndex("Train_name")));
Toast.makeText(Display_data.this, "blahhh:"+temp, Toast.LENGTH_LONG).show();
Log.d("Sucess!","temp:"+temp);
Toast.makeText(Display_data.this, "Gotcha:"+temp , Toast.LENGTH_LONG).show();
namer.setText("Train Name: " + temp);
header.close();
}catch(Exception e)
{
Log.d("Final Error",e.toString());
Toast.makeText(Display_data.this, "Error", Toast.LENGTH_LONG).show();
}
我收到上述错误。有些帖子建议添加“?”但这也没有帮助
这是我插入数据的代码:
try {
final String CREATE_TABLE_TRAIN_LIST = "CREATE TABLE IF NOT EXISTS Train_list ("
+ "Train_name VARCHAR,"
+ "Train_no VARCHAR,"
+ "Train_start VARCHAR,"
+ "Train_end VARCHAR,"
+ "Seats_Available VARCHAR);";
db.execSQL(CREATE_TABLE_TRAIN_LIST);
Toast.makeText(admin_manipulation.this, "Table created", Toast.LENGTH_LONG).show();
String sql = "INSERT or replace INTO Train_list (Train_name, Train_no, Train_start, Train_end, Seats_Available) VALUES('"+str_Train_name + "',' " +str_Train_no + "', '" +str_Train_start+"','" +str_Train_end+"',' " +str_Train_seats +"');";
try {
db.execSQL(sql);
Toast.makeText(admin_manipulation.this, "train no:"+str_Train_no, Toast.LENGTH_SHORT).show();
}catch(Exception e)
{
Toast.makeText(admin_manipulation.this, "Sorry Not Inserted Sucessfully", Toast.LENGTH_SHORT).show();
Log.d("Error experienced",e.toString());
}
知道为什么会发生这种情况吗?
最佳答案
尝试通过获取已运行查询的游标计数来进行检查。 header.getCount()
然后仅当有数据时才执行 header.getString()
if (header!= null && header.getCount() > 0){
header.moveToFirst();
// All the logic of retrieving data from cursor
}
关于android - 即使数据存在于数据库中,也无法从 sqlite 数据库检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182057/