1 /*
2  * Copyright (C) 2012 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 com.android.contacts.common.database;
18 
19 import android.content.AsyncQueryHandler;
20 import android.content.ContentResolver;
21 import android.database.Cursor;
22 import android.net.Uri;
23 
24 /**
25  * An {@AsyncQueryHandler} that will never return a null cursor.
26  * <p>
27  * Instead, will return a {@link Cursor} with 0 records.
28  */
29 public abstract class NoNullCursorAsyncQueryHandler extends AsyncQueryHandler {
30 
NoNullCursorAsyncQueryHandler(ContentResolver cr)31     public NoNullCursorAsyncQueryHandler(ContentResolver cr) {
32         super(cr);
33     }
34 
35     @Override
startQuery(int token, Object cookie, Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy)36     public void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection,
37             String[] selectionArgs, String orderBy) {
38         final CookieWithProjection projectionCookie = new CookieWithProjection(cookie, projection);
39         super.startQuery(token, projectionCookie, uri, projection, selection, selectionArgs,
40                 orderBy);
41     }
42 
43     @Override
onQueryComplete(int token, Object cookie, Cursor cursor)44     protected final void onQueryComplete(int token, Object cookie, Cursor cursor) {
45         CookieWithProjection projectionCookie = (CookieWithProjection) cookie;
46 
47         super.onQueryComplete(token, projectionCookie.originalCookie, cursor);
48 
49         if (cursor == null) {
50             cursor = new EmptyCursor(projectionCookie.projection);
51         }
52         onNotNullableQueryComplete(token, projectionCookie.originalCookie, cursor);
53     }
54 
onNotNullableQueryComplete(int token, Object cookie, Cursor cursor)55     protected abstract void onNotNullableQueryComplete(int token, Object cookie, Cursor cursor);
56 
57     /**
58      * Class to add projection to an existing cookie.
59      */
60     private static class CookieWithProjection {
61         public final Object originalCookie;
62         public final String[] projection;
63 
CookieWithProjection(Object cookie, String[] projection)64         public CookieWithProjection(Object cookie, String[] projection) {
65             this.originalCookie = cookie;
66             this.projection = projection;
67         }
68     }
69 }
70