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());
}
答案 0 :(得分:0)
<强>重写强>
我仍然不明白你想要做什么,但是看看你之前的问题:android searching with multiple keywords,我假设你想要一个这样的查询: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”,“mustache”或“pull”的每一行。