Hye。。我设法创建了使用多个关键字进行搜索的搜索功能。问题是关键字必须存在于我设置的数据库列中。如果我使用3个关键字进行搜索,即数据库中有2个关键字匹配,但还有1个关键字不存在。结果什么也没显示。
如何忽略不存在的关键字??只需获取数据库中存在的关键字即可。也就是说,如果用户输入了很多关键词,系统将只读取数据库中匹配的关键词,而忽略不匹配的关键词。下面是我的代码。
String s = txtLelaki.getText().toString();
String s = txtLelaki.getText().toString();
String[] words = s.split(" ");
String sql = null;
String where = helper.KEY_LELAKI + " = ?";
String relation = " or ";
String wildcard1 = "'%";
String wildcard2 = "%'";
StringBuilder build = null;
for(int i=0;i<words.length; i++)
{
words[i] = new StringBuilder(wildcard1).append(words[i]).append(wildcard2).toString();
if(i==0)
build = new StringBuilder(where);
else
build.append(relation).append(where);
}
Cursor c = database.query(helper.DB_TABLE_LELAKI, null, build.toString(), words, null, null, null);
if(c!= null)
{
c.moveToFirst();
int soalanColumn = c.getColumnIndex(helper.MASALAH_LELAKI);
int getId = c.getColumnIndex(helper.ID_LELAKI);
if(c.isFirst())
{
do
{
idList.add(c.getLong(getId));
results.add(c.getString(soalanColumn));
}while(c.moveToNext());
}
}
adapter.updateList(results);
listView.setTextFilterEnabled(true);
}//end try
catch(SQLException e)
{
Log.v("caer", e.toString());
}
重写
我仍然不清楚你到底想做什么,但看看你之前的问题:android使用多个关键字进行搜索,我认为你想要这样的查询:每个可能的关键字的SELECT * FROM Table WHERE foo like ? OR foo like ? ...
。您需要自己构建这个WHERE
子句:
String where = helper.KEY_LELAKI + " = ?";
String relation = " OR ";
String wildcard = "%";
StringBuilder builder;
for(int i = 0; i < words.length; i++) {
// Surround the keyword with "%", i.e. "%cat%"
words[i] = new StringBuilder(wildcard).append(words[i]).append(wildcard).toString();
// Build the WHERE clause
if(i == 0)
builder = new StringBuilder(where);
else
builder.append(relation).append(where);
}
Cursor c = myDataBase.query(helper.DB_TABLE_LELAKI, null,
builder.toString(), words, null, null, null);
如果示例中的s
是"cat mustache pull"
,那么查询中的每一行都将包含关键字短语"cat"、"splash"或"pull"。