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