2013-03-01 59 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