开发者

Filtering query in database SQLite

开发者 https://www.devze.com 2023-03-04 16:24 出处:网络
I have a table in a database and I would like to show on开发者_Go百科ly one row of this table. The table has 3 fields (ID, Title and Description).

I have a table in a database and I would like to show on开发者_Go百科ly one row of this table. The table has 3 fields (ID, Title and Description). I want to filter the rows depending on the Title.

I have this code:

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

where the third field is the selection one (a String). But I don't know what I have to put exactly to select only the row that I want to show. Thanks


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);

This should give you a cursor with all your columns but only containing the rows where the value of the Title column is equal to 0.


try this

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


You can search by following code in SQLite;

In 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;
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消