2011-02-20 60 views
3

我有一個數據庫,如下所示:FilterQueryProvider,過濾器和ListView

------------------------------ 
BOOK NAME | BOOK FORMAT | COUNT | 
------------------------------ 
Android | HTML  | 1 
WPF  | PDF  | 10 
Symbian | PS   | 2 
Windows | HTML  | 2 

我顯示通過利用CustomSimpleCursorAdapter這個數據庫對用戶進行 。

CustomSimpleCursorAdapter extends SimpleCursorAdapter 

實現可篩選

getView() & runQueryonBackgroundThread()被覆蓋。
正確顯示書籍的網格視圖。

該用戶有以下選項:

HTML | PDF | PS | DELETE

Constraint: BOOK FORMAT 
[HTML - 1, PDF - 2, PS - 3] 

當用戶按下HTML菜單選項,與HTML書籍 類型必須顯示。

MenuOption處理程序中(),我寫如下:

adapter.getFilter().filter("1"); 

runQueryonBackgroundThread() { 
    if(mCursor != null) 
     mCursor.close(); 
    mCursor = query(using the constraint) 
    return mCursor; 
} 

這種約束達到我重寫runQueryonBackgroundThread() 方法。但它不更新網格視圖並引發異常。

「FILTER:android.view.ViewRoot $ CalledFromWrongThreadException:只有創建視圖層次可以觸摸的意見 原來的線程」

請幫助我。

回答

8

我認爲你已經搞混了一些東西。實際上SimpleCursorAdapter已經實現了Filterable,所以不需要重新實現。代替你的ListActivity使用類似這樣的:

private void filterList(CharSequence constraint) { 
    final YourListCursorAdapter adapter = 
     (YourListCursorAdapter) getListAdapter(); 
    final Cursor oldCursor = adapter.getCursor(); 
    adapter.setFilterQueryProvider(filterQueryProvider); 
    adapter.getFilter().filter(constraint, new FilterListener() { 
     public void onFilterComplete(int count) { 
      // assuming your activity manages the Cursor 
      // (which is a recommended way) 
      stopManagingCursor(oldCursor); 
      final Cursor newCursor = adapter.getCursor(); 
      startManagingCursor(newCursor); 
      // safely close the oldCursor 
      if (oldCursor != null && !oldCursor.isClosed()) { 
       oldCursor.close(); 
      } 
     } 
    }); 
} 

private FilterQueryProvider filterQueryProvider = new FilterQueryProvider() { 
    public Cursor runQuery(CharSequence constraint) { 
     // assuming you have your custom DBHelper instance 
     // ready to execute the DB request 
     return dbHelper.getListCursor(constraint); 
    } 
}; 
+0

嗨Arhimed,非常感謝。它效果很好。 :)我也會嘗試在CustomSimpleCursorAdapter的runQueryonBT中做到這一點。 – ramsarvan

+0

這很有趣。這在使用裝載機時仍然有效嗎?我的意思是使用過濾器查詢提供程序比簡單地執行restartLoader()有什麼優勢?看到我的問題http://stackoverflow.com/questions/24344950/filtering-with-loadermanager-and-content-provider – faizal

+0

@faizal:我還沒有深入調查裝載機,所以沒有權利向你提出任何建議。 –