2013-03-01 54 views
0

Hye..I设法创建搜索功能,使用多个关键字进行搜索。问题是关键字必须存在于我设置的数据库列中。如果我使用3个关键字进行搜索,即2个关键字匹配数据库内部,但不存在1个关键字。结果什么也没有显示。android在搜索功能中忽略不存在的关键字

我怎么能忽略不存在的关键字?只需要在我的数据库中存在的关键字。意思是,如果用户输入很多关键字,系统将只读取仅匹配我的数据库内的关键字,并且会忽略不匹配的关键字。以下是我的代码。

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

重写
我还是不明白,正是你想做的事,但看着你前面的问题: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"您的查询就会有一个包含关键字词组“猫”中的每一行,“小胡子”,或“拉”。

+0

对不起,如果我的文章是不完整的..我编辑我的问题,添加一些代码。 – iWantToLearn 2013-03-02 06:22:33

+0

我更新了我的答案,也许这会有所帮助。 – Sam 2013-03-02 17:46:14

+0

我曾尝试过你的代码..它显示没有错误...但是当我试图输入关键字时,它不会在我的列表视图中显示任何内容..我也尝试调试,当输入3个关键字时,它看起来没有问题,因为它循环3次内循环...我会更新我的代码上面为您检查.. ~~ – iWantToLearn 2013-03-03 07:09:35