【发布时间】:2018-04-19 23:07:56
【问题描述】:
这是将项目插入我的名为Train_List的数据库的代码\
SQLiteDatabase db = openOrCreateDatabase( "Train_list.db", SQLiteDatabase.CREATE_IF_NECESSARY , null);
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());
}
我观察到没有exceptions 被抛出,logcat 中也没有任何条目。从而使我相信数据成功
插入。
这是检索插入的数据的代码:
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 * From Train_list Where Train_no='"+message.substring(0,(message.length()-3))+ "'", null);
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);
}catch(Exception e)
{
Log.d("Final Error",e.toString());
Toast.makeText(Display_data.this, "Error", Toast.LENGTH_LONG).show();
}
这会引发异常
D/Final Error: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
通过一点谷歌搜索,我知道当null 返回到游标时会引发此错误,我不明白为什么会发生这种情况,任何人都将不胜感激!
【问题讨论】:
-
如果你在数据库上运行查询 ""Select * From Train_list Where Train_no='"+message.substring(0,(message.length()-3))+ "'""返回任何行?
-
你应该经常检查光标是否为 !在访问其对象之前为空。 cursor.moveToFirst(); while (!cursor.isAfterLast()) { cursor.getLong(0) } 等
-
您发布的代码似乎不是产生该特定异常的代码:您从一开始就从未将光标移动到索引 0。
-
@AmodGokhale 你说的跑步是什么意思?抱歉,我对此有点陌生
-
如果你有独立的数据库 Train_list.db 并且如果你在那里运行 select * from 命令......它会返回任何记录吗?如果不是,那么您的选择查询不正确
标签: android mysql sqlite android-studio indexoutofboundsexception