Couldn't read row 0, col -1 from CursorWindow

java.lang.IllegalStateException: Couldn‘t read row 0, col -1 from CursorWindow. 
Make sure the Cursor is initialized correctly before accessing data from it. 
 
SQLiteDatabase  学习过程中,使用query() 查询表单数据时,遇到Couldn‘t read row 0, col -1 from CursorWindow错误。
排除建表字段错误、拼写错误、query()输入字段错误。当我使用rawQuery()方法取代query()方法,问题就解决了。
 
代码如下:
1.建表 MyDatabaseHelper
 1     private static final String CREATE_CONTACTS = "create table contact ("
 2             + "id integer primary key autoincrement, "
 3             + "name text, "
 4             + "number text )";
 5 
 6     public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
 7         super(context, name, factory, version);
 8     }
 9 
10     @Override
11     public void onCreate(SQLiteDatabase db) {
12         db.execSQL(CREATE_CONTACTS);        
13     }
2.查询 根据searchName查询表单
 1     private void searchContact(String searchName) {
 2         db = dbHelper.getReadableDatabase();
 3         //Cursor cursor = db.query("contact", new String[] {"name"}, "name = ?", new String[] {searchName}, null, null, null); 
 4         Cursor cursor = db.rawQuery("select * from contact where name = ?", new String[] {searchName});
 5         if(cursor.moveToFirst()) {
 6             //String name = cursor.getString(cursor.getColumnIndex("name"));
 7             String number = cursor.getString(cursor.getColumnIndex("number"));
 8             tv_name.setText(searchName);
 9             tv_number.setText(number);
10             tel = "tel:" + number;
11         }else {
12             tv_name.setText("404! Not Found");
13             tv_number.setText("10086");
14             tel = "tel:10086";
15         }
16         cursor.close();
17         db.close();
18     }

1.当使用query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)

String name = cursor.getString(cursor.getColumnIndex("name")) 

用这句代码检验 可以获得到name,证明cursor正确指向所要查询数据。

String number = cursor.getString(cursor.getColumnIndex("number"))

但这句代码就会报Couldn‘t read row 0, col -1 from CursorWindow。

getColumnIndex("number") 返回值竟然是-1,百思不得其解!

 

2.使用rawQuery(String sql, String[] selectionArgs)

name和number字段都可以准确获得,问题完美解决。

 

转载请注明出处:http://www.cnblogs.com/michaelwong/p/4128299.html

 

Couldn't read row 0, col -1 from CursorWindow

上一篇:nfs的优化


下一篇:C# 全局唯一标识符 (GUID)