| 1 | /* |
| 2 | * Copyright (C) 2011 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package android.support.v2.widget; |
| 18 | |
| 19 | import android.database.Cursor; |
| 20 | import android.widget.Filter; |
| 21 | |
| 22 | /** |
| 23 | * <p>The CursorFilter delegates most of the work to the CursorAdapter. |
| 24 | * Subclasses should override these delegate methods to run the queries |
| 25 | * and convert the results into String that can be used by auto-completion |
| 26 | * widgets.</p> |
| 27 | */ |
| 28 | class CursorFilter extends Filter { |
| 29 | |
| 30 | CursorFilterClient mClient; |
| 31 | |
| 32 | interface CursorFilterClient { |
| 33 | CharSequence convertToString(Cursor cursor); |
| 34 | Cursor runQueryOnBackgroundThread(CharSequence constraint); |
| 35 | Cursor getCursor(); |
| 36 | void changeCursor(Cursor cursor); |
| 37 | } |
| 38 | |
| 39 | CursorFilter(CursorFilterClient client) { |
| 40 | mClient = client; |
| 41 | } |
| 42 | |
| 43 | @Override |
| 44 | public CharSequence convertResultToString(Object resultValue) { |
| 45 | return mClient.convertToString((Cursor) resultValue); |
| 46 | } |
| 47 | |
| 48 | @Override |
| 49 | protected FilterResults performFiltering(CharSequence constraint) { |
| 50 | Cursor cursor = mClient.runQueryOnBackgroundThread(constraint); |
| 51 | |
| 52 | FilterResults results = new FilterResults(); |
| 53 | if (cursor != null) { |
| 54 | results.count = cursor.getCount(); |
| 55 | results.values = cursor; |
| 56 | } else { |
| 57 | results.count = 0; |
| 58 | results.values = null; |
| 59 | } |
| 60 | return results; |
| 61 | } |
| 62 | |
| 63 | @Override |
| 64 | protected void publishResults(CharSequence constraint, FilterResults results) { |
| 65 | Cursor oldCursor = mClient.getCursor(); |
| 66 | |
| 67 | if (results.values != null && results.values != oldCursor) { |
| 68 | mClient.changeCursor((Cursor) results.values); |
| 69 | } |
| 70 | } |
| 71 | } |