利用rawQuery(String sql, String[] selectionArgs)查询表中的的数据

开始写的代码是这样子的:

private void findData(){
    sqLiteDatabase=dbHelper.getWritableDatabase();
    Cursor cursor = sqLiteDatabase.rawQuery("select id as _id,name from searchHisTab", null);
    Log.d("TAG","查找表中的数据");
    Log.d(TAG,"cursor的数据为:"+cursor.getCount());
    cursor.moveToFirst();
    do{
        String id= cursor.getString(cursor.getColumnIndex("id"));
        Log.i("TAG","表searchHisTab的id="+id);
        String name = cursor.getString(cursor.getColumnIndex("name"));
        Log.i("TAG","表searchHisTab的name="+name);
    }while(cursor.moveToNext());
    cursor.close();
    sqLiteDatabase.close();
}

出现错误:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.administrator.madioplayer2/com.example.administrator.madioplayer2.Search}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.                                                        

原因:

在使用rawQuery(String sql, String[] selectionArgs)的时候,查询语句一定要有_id,也就是

Cursor cursor = sqLiteDatabase.rawQuery("select id as _id,name from searchHisTab", null);
还有这里的列要是_id,而不能是id 
String id= cursor.getString(cursor.getColumnIndex("id"));

修改:

private void findData(){
    sqLiteDatabase=dbHelper.getWritableDatabase();
    Cursor cursor = sqLiteDatabase.rawQuery("select id as _id,name from searchHisTab", null);
    Log.d("TAG","查找表中的数据");
    Log.d(TAG,"cursor的数据为:"+cursor.getCount());
    cursor.moveToFirst();
    do{
        String id= cursor.getString(cursor.getColumnIndex("_id"));
        Log.i("TAG","表searchHisTab的id="+id);
        String name = cursor.getString(cursor.getColumnIndex("name"));
        Log.i("TAG","表searchHisTab的name="+name);
    }while(cursor.moveToNext());
    cursor.close();
    sqLiteDatabase.close();
}
运行就没有问题了

你可能感兴趣的:(Andriod,Studio遇到的问题/解答)