2016-04-05 166 views
0

我想用像%userCriteria%這樣的LIKE語句來查詢我的數據庫。我有一個表有以下的列(存儲在MySQLiteHelper):SQLite LIKE選擇不起作用

 MySQLiteHelper.COLUMN_DESCRIPTION, 
     MySQLiteHelper.COLUMN_PUB_DATE, 
     MySQLiteHelper.COLUMN_TITLE, 
     MySQLiteHelper.COLUMN_USER_SPEC_NAME, 
     MySQLiteHelper.COLUMN_LINK 

我想創建一個查詢它只會返回在TITLE列含有特定字符串的條目。

我的方法,我實現(也應該執行查詢)是我的dataSourseClass看起來像這樣:

public ArrayList<RssItem> read(String selection, String[] selectionArgs, String groupBy, String having, String orderBy) { 
    ArrayList<RssItem> tasks = new ArrayList<RssItem>(); 

    Cursor cursor = mDatabase.query(MySQLiteHelper.TABLE_NAME, new String[]{allColumns[3]}, selection, selectionArgs, groupBy, having, orderBy); 

    cursor.moveToFirst(); 
    while (!cursor.isAfterLast()) { 
     RssItem task = cursorToTask(cursor); 
     tasks.add(task); 
     cursor.moveToNext(); 
    } 
    // Make sure to close the cursor 
    cursor.close(); 
    return tasks; 

} 

allColumns:

private String[] allColumns = { 
     MySQLiteHelper.COLUMN_ID, 
     MySQLiteHelper.COLUMN_DESCRIPTION, 
     MySQLiteHelper.COLUMN_PUB_DATE, 
     MySQLiteHelper.COLUMN_TITLE, 
     MySQLiteHelper.COLUMN_USER_SPEC_NAME, 
     MySQLiteHelper.COLUMN_LINK 
}; 

這是我如何打電話我的活動中的閱讀方法:

private void searchDatabase(String searchCriteriaTitle) { 
    //clear the data from the adapter... 
    mAdapter.clear(); 
    //get all of the stored records (during the parsing process)... 
    List<RssItem> items = rssItemDataSource.read(MySQLiteHelper.COLUMN_TITLE + " LIKE ?",new String[]{searchCriteriaTitle},null,null,null); 

    //if the search criteria is not empty string... 
    if(!searchedItem.equals("")){ 
     for(int i = 0; i < items.size();i++) { 
      //search from a match against the user's search criteria... 

      mAdapter.add(items.get(i)); 

     } 
    } 
    //if the search criteria is am empty string... 
    else{ 
     //read all of the 
     List<RssItem> allItems = rssItemDataSource.getAllTasks(); 
     //add all... 
     for(int i = 0; i < allItems.size();i++) { 
      mAdapter.add(allItems.get(i)); 
     } 
    } 
} 

現在,返回的條目列表是空的,我不明白爲什麼。有什麼建議麼?

回答

2

你試過了嗎?

List<RssItem> items = rssItemDataSource.read(MySQLiteHelper.COLUMN_TITLE + " LIKE ?", new String[]{"%"+searchCriteriaTitle+"%"},null,null,null); 
+1

謝謝。這就是訣竅!欣賞它:) –

+1

@GeorgiKoemdzhiev喲歡迎budy! –

0

你可以嘗試

Cursor cursor = mDatabase rawQuery("select "+COLUMN_TITLE +"from "+MySQLiteHelper.TABLE_NAME+" where "+MySQLiteHelper.COLUMN_TITLE+" LIKE \'?\'", new String[]{"userCriteria"}); 
    if(cursor.moveToFirst()){ 
     do { 
      RssItem task = cursorToTask(cursor); 
      tasks.add(task); 
      cursor.moveToNext(); 
    }while (cursor.moveToNext()); 
} 
+0

謝謝你的建議。我確實嘗試過使用rawQuery,但它看起來更復雜,所以我堅持查詢。感謝您的幫助:) –

+2

@ georgi-koemdzhiev:很高興你解決了它:)快樂編碼哥們:) –