【发布时间】:2011-08-22 08:49:21
【问题描述】:
我在数据库中有一个表,我想只显示该表的一行。该表有 3 个字段(ID、标题和描述)。 我想根据标题过滤行。
我有这个代码:
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
其中第三个字段是选择项(字符串)。但我不知道我必须准确地选择我想要显示的行。谢谢
【问题讨论】:
我在数据库中有一个表,我想只显示该表的一行。该表有 3 个字段(ID、标题和描述)。 我想根据标题过滤行。
我有这个代码:
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
其中第三个字段是选择项(字符串)。但我不知道我必须准确地选择我想要显示的行。谢谢
【问题讨论】:
试试这个
Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);
【讨论】:
String[] FROM = { // ID of the column(s) you want to get in the cursor
ID,
Title,
Description
};
String where = "Title=?"; // the condition for the row(s) you want returned.
String[] whereArgs = new String[] { // The value of the column specified above for the rows to be included in the response
"0"
};
return db.query(TABLE_NAME, FROM, where, whereArgs, null, null, null);
这应该会给你一个包含所有列的光标,但只包含 Title 列的值等于 0 的行。
【讨论】:
您可以在SQLite中通过以下代码进行搜索;
在 MainActivity 中;
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return
//Here you can filter data by any row , just change text replace of "subject"
dbManager.fetchdatabyfilter(constraint.toString(),"subject");
}
});
DatabaseHelper.java
public Cursor fetchdatabyfilter(String inputText,String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM "+DatabaseHelper.TABLE_NAME;
if (inputText == null || inputText.length () == 0) {
row = database.rawQuery(query, null);
}else {
query = "SELECT * FROM "+DatabaseHelper.TABLE_NAME+" WHERE "+filtercolumn+" like '%"+inputText+"%'";
row = database.rawQuery(query, null);
}
if (row != null) {
row.moveToFirst();
}
return row;
}
【讨论】: