[英]SQLite cursor returning IllegalStateException?
我正在嘗試向數據庫添加元素,然后搜索特定條目。 但是我收到一個游標錯誤。 這是我的 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.
原因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.
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);
}
請記住,如果您更改了數據庫中的任何內容,則應升級數據庫版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.