我试图从名为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());
}
知道为什么会这样吗?
答案 0 :(得分:0)
尝试通过获取已运行查询的光标计数来进行检查。 header.getCount()
然后仅在有数据的情况下执行header.getString()
if (header!= null && header.getCount() > 0){
header.moveToFirst();
// All the logic of retrieving data from cursor
}
答案 1 :(得分:0)
代码中的这一行:
header = db1.rawQuery("Select Train_name From Train_list Where Train_no='"+message.substring(0,(message.length()-3))+ "'", null);
可能会出现问题,具体取决于传入的message
。
如果Train_no
应该是表格中的列车编号,则子字符串 - 3看起来只会返回" aa"一部分。然后你的rawQuery将寻找一个Train_no
,这是" aa"。
考虑使用LIKE SQL语法。 This question is useful
您的查询可能如下所示:
header = db1.rawQuery("Select Train_name From Train_list Where Train_no like '"+message.substring((message.length()-3), message.length())+ "'", null);