我正在尝试过滤listView中的项目,但它无法正常工作。似乎我的代码没有响应我的editText中输入的文本。
这是我的SearchActivity类(MainActivity)
public class SearchActivity extends Activity {
private DatabaseHelper myDatabaseHelper;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
ListView listContent = (ListView)findViewById(R.id.contentlist);
myDatabaseHelper = new DatabaseHelper(this);
try {
myDatabaseHelper.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myDatabaseHelper.openDataBase();
Cursor cursor = myDatabaseHelper.queueAll();
startManagingCursor(cursor);
String[] from = new String[]{DatabaseHelper.KEY_CONTENT};
int[] to = new int[]{R.id.text1};
final SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
listContent.setFastScrollEnabled(true);
listContent.setTextFilterEnabled(true);
EditText etext=(EditText)findViewById(R.id.editText1);
etext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
ListView listContent2 = (ListView)findViewById(R.id.contentlist);
SimpleCursorAdapter filterAdapter = (SimpleCursorAdapter)listContent2.getAdapter();
filterAdapter.getFilter().filter(s.toString());
}
});
cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return myDatabaseHelper.getDirectoryList(constraint);
}
});
myDatabaseHelper.close();
这是我的getDirectoryList
public Cursor getDirectoryList (CharSequence constraint) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(DB_NAME);
String[] columns = new String[]{KEY_ID, KEY_CONTENT, KEY_DESCRIPTION, KEY_NETWORKING, KEY_HARDWARE, KEY_SOFTWARE, KEY_INTERNET, KEY_TECHNOLOGY};
if (constraint == null || constraint.length () == 0) {
// Return the full list
Cursor cursor = myDataBase.query("MY_TABLE",
columns, null, null, null, null, null);
return cursor;
} else {
String value = constraint.toString()+"%";
Cursor cursor2 = myDataBase.query("MY_TABLE", columns, "KEY_CONTENT like ?", new String[]{value}, null, null, null);
return cursor2;
}
}
}