我正在尝试向数据库中添加元素,然后搜索特定条目。但是我得到了一个光标错误。这是我为DB类编写的代码。数据库只包含一列。提前谢谢。
public class DataB extends SQLiteOpenHelper {
private static final String db_name = "testing.db";
private static final int version = 1;
private static final String table_name = "students";
private static final String col_name="FirstName";
public DataB(Context context) {
super(context, db_name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String q = "CREATE TABLE " + table_name + " (FirstName TEXT PRIMARY KEY) ";
db.execSQL(q);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+table_name);
onCreate(db);
}
public int addData(String name)
{
ContentValues cv = new ContentValues();
cv.put(col_name, name);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(table_name, null, cv);
db.close();
return 1;
}
public String search(String string)
{
String dbstring=" ";
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM "+ table_name + " WHERE FirstName = '" + string+"'";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
while(!c.isAfterLast())
{
if(c.getString(c.getColumnIndex("FirstName"))!=null)
{
dbstring = c.getString(c.getColumnIndex("FirstName"));
}
}
return dbstring;
}
}
错误是Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
while根本不起作用,你永远不会改变光标的位置,所以它总是真的会产生堆叠式
执行查询后,您应该询问光标是否为空,以及是否可以移动到第一个位置,如下所示:
if(c != null && c.moveToFirst()){
dbstring = c.getString(c.getColumnIndex(col_name));
}
或者,在你的情况下,因为你唯一的列是FirstName,所以你可以这样看:
if(c != null && c.moveToFirst()){
dbstring = c.getString(0);
}
请记住,如果更改数据库中的任何内容,则应升级数据库版本。