在数据库SQLite中过滤查询

时间:2011-05-10 10:35:33

标签: android sqlite filtering

我在数据库中有一个表,我想只显示该表的一行。该表有3个字段(ID,标题和描述)。 我想根据标题过滤行。

我有这段代码:

Cursor cursor = db.query(TABLE_NAME,FROM,null,null,null,null,ORDER_BY);

其中第三个字段是选择字段(字符串)。但我不知道我必须准确选择我想要显示的行。感谢

3 个答案:

答案 0 :(得分:6)

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的行。

答案 1 :(得分:1)

试试这个

Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);

答案 2 :(得分: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;
 }