Java CursorIndexOutOfBoundsException?
我想使用List和Cursor将两个值放入SQLite数据库中的一个微调器行,下面是我的代码: 将数据放入列表:Java CursorIndexOutOfBoundsException?,java,android,sqlite,android-sqlite,indexoutofboundsexception,Java,Android,Sqlite,Android Sqlite,Indexoutofboundsexception,我想使用List和Cursor将两个值放入SQLite数据库中的一个微调器行,下面是我的代码: 将数据放入列表: public List<String> getAllLabelsServer(){ List<String> labels = new ArrayList<String>(); // Select All Query String selectQuery = "SELECT ip FROM "
public List<String> getAllLabelsServer(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT ip FROM " + ServerEntry.TABLE_NAME;
String description = "SELECT description FROM " + ServerEntry.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Cursor cursor1 = db.rawQuery(description, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String multiRow = cursor.getString(0) + " - " + cursor1.getString(0);
labels.add(multiRow);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
如何解决此错误?仅使用一个光标获取两列
String sql = "SELECT ip,description FROM " + ServerEntry.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
while(cursor.moveToNext()) {
String multiRow = cursor.getString(cursor.getColumnIndex("ip")) + " - " + cursor.getString(cursor.getColumnIndex("description"));
labels.add(multiRow);
}
仅使用一个光标获取两列
String sql = "SELECT ip,description FROM " + ServerEntry.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
while(cursor.moveToNext()) {
String multiRow = cursor.getString(cursor.getColumnIndex("ip")) + " - " + cursor.getString(cursor.getColumnIndex("description"));
labels.add(multiRow);
}
您在第一条记录上只移动了一个2游标(名为
游标的游标)
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String multiRow = cursor.getString(0) + " - " + cursor1.getString(0);
labels.add(multiRow);
} while (cursor.moveToNext());
}
因此,第二个(名为cursor1
)仍然指向索引-1
因此,这是一个例外
Index -1 requested, with a size of 2
请允许我问你为什么你要执行两个不同的查询,而你却可以用一个来获得所有必需的字段
i、 e:
然后你只需要处理一个单光标。你只移动了第一条记录上的2个光标中的一个(名为光标
)
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String multiRow = cursor.getString(0) + " - " + cursor1.getString(0);
labels.add(multiRow);
} while (cursor.moveToNext());
}
因此,第二个(名为cursor1
)仍然指向索引-1
因此,这是一个例外
Index -1 requested, with a size of 2
请允许我问你为什么你要执行两个不同的查询,而你却可以用一个来获得所有必需的字段
i、 e:
然后你只需要处理一个单光标。建议:在使用ListView和数据库时使用CursorAdapter建议:在使用ListView和数据库时使用CursorAdapter