我使用searchView获取查询以使用字符串搜索数据库,Cursor不会返回null但是为空。
从我的搜索活动(实现SearchView.OnQueryTextListener的ListActivity)调用搜索:
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
//handleIntent(intent);
Log.d("LIST ACTIVITY SEARCH", "onQueryTextCahanged called: "+ newText);
Cursor c = data.getWordMatches(newText, null);
Log.d("LISTACTIVITY", "CURSOR QUERY ROWS/COLS = "+ c.getCount()+" "+c.getColumnCount());
//now set bind cursor data to list view using custim ItemAdpter class
adapter = new ItemAdapter(ViewListOfTests.this, c);
this.setListAdapter(adapter);
return false;
}
SQLite Database中的搜索方法从上面的方法获取String查询:
/*
* methods to search database with String query form searchable widget intent
* in ViewListOfDives ListActivity search bar. Each search returns a cursor which is set to adpter
* in ViewListOfYesys List Activity
*/
public Cursor getWordMatches(String query, String[] columns){
String selection = database.KEY_TESTNAME + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"}; //wildcard *
return query(selection, selectionArgs, columns);
}//end getWordMatches
private Cursor query(String selection, String[] selectionArgs,
String[] columns) {
// return cursor form params passed getWordMatches(Styring query) from search widget ListActivity
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(DATABASE_TABLE);
dbHelperObject = new DbHelper(ourContext);
Cursor cursor = builder.query(dbHelperObject.getReadableDatabase(), columns, selection, selectionArgs, null, null, null);
if(cursor == null){
return null;
}else if(!cursor.moveToFirst()){
cursor.close();
return null;
}
return cursor;
}//end query
如果代码在这里执行,则返回一个空游标:
else if(!cursor.moveToFirst()){
cursor.close();
return null;
任何输入赞赏! 夏兰
答案 0 :(得分:2)
而不是:
if(cursor == null){
return null;
}else if(!cursor.moveToFirst()){
cursor.close();
return null;
}
return cursor;
用此:
if(cursor == null){
return null;
}else{
cursor.moveToFirst();
}
return cursor;
答案 1 :(得分:0)
知道了,好像我把错误的参数传递给了curosr.rawQuery()。 我正在将ref传递给dataBase帮助对象getReadableDB调用:
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
当我用数据库对象替换此参数时,它工作正常:
SQLiteDatabase ourDataBase = ourDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor cursor = builder.query(ourDataBase, columns, selection, selectionArgs, null, null, null);
所述的培训文档通过了前mDatabaseOpenHelper.getReadableDatabase(),但这似乎不起作用,而不是原因。http://developer.android.com/training/search/search.html