Example usage for android.database.sqlite SQLiteQueryBuilder appendWhere

List of usage examples for android.database.sqlite SQLiteQueryBuilder appendWhere

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteQueryBuilder appendWhere.

Prototype

public void appendWhere(@NonNull CharSequence inWhere) 

Source Link

Document

Append a chunk to the WHERE clause of the query.

Usage

From source file:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    //        Log.d(TAG, "Managed query: " + uri);
    String groupBy = null;/*from  w ww .  j  a  va  2s. co  m*/
    String orderBy = null;
    String limit = null;
    switch (sUriMatcher.match(uri)) {
    case BOOKMARKS_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(bookmarksProjectionMap);

        String labelID = uri.getQueryParameter("label_id");
        if (labelID != null) {
            qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id");
            qb.appendWhere("bookmark_labels.label_id=?");
            selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelID });
        }
        break;

    case BOOKMARK_SEARCH_URI:
    case BOOKMARK_SEARCH_SUGGEST_URI:
        String query = null;
        if (sUriMatcher.match(uri) == BOOKMARK_SEARCH_SUGGEST_URI) {
            qb.setProjectionMap(searchSuggestProjectionMap);
            // path looks like "search_suggest_query/[query]?limit=50
            query = uri.getLastPathSegment();
            limit = uri.getQueryParameter("limit");
            if (sortOrder == null)
                sortOrder = Bookmark.Columns.SORT_MODIFIED;
        } else
            query = uri.getQueryParameter("q");

        if (query != null) {
            qb.setTables("bookmarks join bookmarks_FTS on bookmarks._id = bookmarks_FTS.docid");
            qb.appendWhere("bookmarks_FTS MATCH ?");
            if (selectionArgs == null)
                selectionArgs = new String[] { query };
            else
                selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { query });
        } else if (selectionArgs == null || selectionArgs.length < 1)
            throw new IllegalArgumentException("No search criteria given for query!");
        break;

    case BOOKMARK_ID_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(bookmarksProjectionMap);
        qb.appendWhere(Bookmark.Columns._ID + "=" + uri.getPathSegments().get(1));
        break;

    case LABELS_URI:
        qb.setTables("labels join bookmark_labels on labels._id = bookmark_labels.label_id");
        groupBy = "label";
        if (sortOrder == null)
            sortOrder = Label.Columns.DEFAULT_SORT_ORDER;
        qb.setProjectionMap(labelsProjectionMap);
        break;

    case LIVE_FOLDER_BOOKMARKS_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(sLiveFolderProjectionMap);
        String labelId = uri.getQueryParameter("label_id");
        if (labelId != null) {
            qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id");
            qb.appendWhere("bookmark_labels.label_id=?");
            selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelId });
        }
        sortOrder = "modified DESC"; // for some reason this gets set to 'name ASC'
        break;

    case BOOKMARK_LISTS_URI:
        qb.setTables(BookmarkList.TABLE_NAME);
        qb.setProjectionMap(listsProjectionMap);
        if (sortOrder == null)
            sortOrder = BookmarkList.Columns.DEFAULT_SORT_ORDER;
        String type = uri.getQueryParameter(BookmarkList.PARAM_CATEGORY);
        if (BookmarkList.LISTS_PRIVATE.equals(type))
            qb.appendWhere("owned=1");
        else if (BookmarkList.LISTS_SHARED.equals(type))
            qb.appendWhere("shared=1");
        else if (BookmarkList.LISTS_PUBLIC.equals(type))
            qb.appendWhere("publshed=1");
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    // If no sort order is specified use the default
    if (TextUtils.isEmpty(sortOrder)) {
        orderBy = Bookmark.Columns.DEFAULT_SORT_ORDER;
    } else {
        orderBy = sortOrder;
    }

    // Get the database and run the query
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy, limit);

    // Tell the cursor what uri to watch, so it knows when its source data changes
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private Cursor querySource(@NonNull final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    ContentResolver contentResolver = getContext() != null ? getContext().getContentResolver() : null;
    if (contentResolver == null) {
        return null;
    }/* ww w.j a va  2s  .  com*/
    final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(MuzeiContract.Sources.TABLE_NAME);
    qb.setProjectionMap(allSourcesColumnProjectionMap);
    final SQLiteDatabase db = databaseHelper.getReadableDatabase();
    if (MuzeiProvider.uriMatcher.match(uri) == SOURCE_ID) {
        // If the incoming URI is for a single source identified by its ID, appends "_ID = <sourceId>"
        // to the where clause, so that it selects that single source
        qb.appendWhere(BaseColumns._ID + "=" + uri.getLastPathSegment());
    }
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
        orderBy = MuzeiContract.Sources.DEFAULT_SORT_ORDER;
    else
        orderBy = sortOrder;
    final Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy, null);
    c.setNotificationUri(contentResolver, uri);
    return c;
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private Cursor queryArtwork(@NonNull final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    ContentResolver contentResolver = getContext() != null ? getContext().getContentResolver() : null;
    if (contentResolver == null) {
        return null;
    }/*  w  w w. ja v a2 s. c o m*/
    final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(MuzeiContract.Artwork.TABLE_NAME + " INNER JOIN " + MuzeiContract.Sources.TABLE_NAME + " ON "
            + MuzeiContract.Artwork.TABLE_NAME + "." + MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME
            + "=" + MuzeiContract.Sources.TABLE_NAME + "." + MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME);
    qb.setProjectionMap(allArtworkColumnProjectionMap);
    final SQLiteDatabase db = databaseHelper.getReadableDatabase();
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        // If the incoming URI is for a single source identified by its ID, appends "_ID = <artworkId>"
        // to the where clause, so that it selects that single piece of artwork
        qb.appendWhere(
                MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + "=" + uri.getLastPathSegment());
    }
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
        orderBy = MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED + " DESC, "
                + MuzeiContract.Artwork.DEFAULT_SORT_ORDER;
    else
        orderBy = sortOrder;
    final Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy, null);
    c.setNotificationUri(contentResolver, uri);
    return c;
}

From source file:com.fututel.db.DBProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String finalSortOrder = sortOrder;
    String[] finalSelectionArgs = selectionArgs;
    String finalGrouping = null;//  www .ja v  a  2 s.c  o  m
    String finalHaving = null;
    int type = URI_MATCHER.match(uri);

    Uri regUri = uri;

    int remoteUid = Binder.getCallingUid();
    int selfUid = android.os.Process.myUid();
    if (remoteUid != selfUid) {
        if (type == ACCOUNTS || type == ACCOUNTS_ID) {
            for (String proj : projection) {
                if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) {
                    throw new SecurityException("Password not readable from external apps");
                }
            }
        }
    }

    Cursor c;
    long id;
    switch (type) {
    case ACCOUNTS:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC";
        }
        break;
    case ACCOUNTS_ID:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        qb.appendWhere(SipProfile.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case CALLLOGS:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = CallLog.Calls.DATE + " DESC";
        }
        break;
    case CALLLOGS_ID:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        qb.appendWhere(CallLog.Calls._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case FILTERS:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = Filter.DEFAULT_ORDER;
        }
        break;
    case FILTERS_ID:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        qb.appendWhere(Filter._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case MESSAGES:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        break;
    case MESSAGES_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        qb.appendWhere(SipMessage.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case THREADS:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL,
                SipMessage.FIELD_TO,
                "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN "
                        + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM
                        + " END AS message_ordering",
                SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE,
                "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ,
                //SipMessage.FIELD_READ,
                "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" };
        //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX
        //        + "," + SipMessage.MESSAGE_TYPE_SENT + ")");
        finalGrouping = "message_ordering";
        regUri = SipMessage.MESSAGE_URI;
        break;
    case THREADS_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO,
                SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE,
                SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL };
        qb.appendWhere(MESSAGES_THREAD_SELECTION);
        String from = uri.getLastPathSegment();
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { from, from });
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        synchronized (profilesStatus) {
            ContentValues[] cvs = new ContentValues[profilesStatus.size()];
            int i = 0;
            for (ContentValues ps : profilesStatus.values()) {
                cvs[i] = ps;
                i++;
            }
            c = getCursor(cvs);
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    case ACCOUNTS_STATUS_ID:
        id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            ContentValues cv = profilesStatus.get(id);
            if (cv == null) {
                return null;
            }
            c = getCursor(new ContentValues[] { cv });
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder);

    c.setNotificationUri(getContext().getContentResolver(), regUri);
    return c;
}

From source file:com.sonetel.db.DBProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String finalSortOrder = sortOrder;
    String[] finalSelectionArgs = selectionArgs;
    String finalGrouping = null;//  w  ww . j av  a  2 s  . c om
    String finalHaving = null;
    int type = URI_MATCHER.match(uri);

    Uri regUri = uri;

    int remoteUid = Binder.getCallingUid();
    int selfUid = android.os.Process.myUid();
    if (remoteUid != selfUid) {
        if (type == ACCOUNTS || type == ACCOUNTS_ID) {
            for (String proj : projection) {
                if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) {
                    throw new SecurityException("Password not readable from external apps");
                }
            }
        }
    }

    Cursor c;
    long id;
    switch (type) {
    case ACCOUNTS:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC";
        }
        break;
    case ACCOUNTS_ID:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        qb.appendWhere(SipProfile.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case CALLLOGS:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = CallLog.Calls.DATE + " DESC";
        }
        break;
    case CALLLOGS_ID:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        qb.appendWhere(CallLog.Calls._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case FILTERS:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = Filter.DEFAULT_ORDER;
        }
        break;
    case FILTERS_ID:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        qb.appendWhere(Filter._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case MESSAGES:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        break;
    case MESSAGES_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        qb.appendWhere(SipMessage.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case THREADS:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL,
                SipMessage.FIELD_TO,
                "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN "
                        + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM
                        + " END AS message_ordering",
                SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE,
                "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ,
                //SipMessage.FIELD_READ,
                "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" };
        //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX
        //        + "," + SipMessage.MESSAGE_TYPE_SENT + ")");
        finalGrouping = "message_ordering";
        regUri = SipMessage.MESSAGE_URI;
        break;
    case THREADS_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO,
                SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE,
                SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL };
        qb.appendWhere(MESSAGES_THREAD_SELECTION);
        String from = uri.getLastPathSegment();
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { from, from });
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        synchronized (profilesStatus) {
            ContentValues[] cvs = new ContentValues[profilesStatus.size()];
            int i = 0;
            for (ContentValues ps : profilesStatus.values()) {
                cvs[i] = ps;
                i++;
            }
            c = getCursor(cvs);
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    case ACCOUNTS_STATUS_ID:
        id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            ContentValues cv = profilesStatus.get(id);
            if (cv == null) {
                return null;
            }
            c = getCursor(new ContentValues[] { cv });
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    case ACCESSNO:
        qb.setTables(SipProfile.ACCESS_NUMS_TABLE_NAME);

        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder);

    c.setNotificationUri(getContext().getContentResolver(), regUri);
    return c;
}

From source file:com.csipsimple.db.DBProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String finalSortOrder = sortOrder;
    String[] finalSelectionArgs = selectionArgs;
    String finalGrouping = null;// w ww  .  j a  v a 2 s. c  om
    String finalHaving = null;
    int type = URI_MATCHER.match(uri);

    Uri regUri = uri;

    // Security check to avoid data retrieval from outside
    int remoteUid = Binder.getCallingUid();
    int selfUid = android.os.Process.myUid();
    if (remoteUid != selfUid) {
        if (type == ACCOUNTS || type == ACCOUNTS_ID) {
            for (String proj : projection) {
                if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) {
                    throw new SecurityException("Password not readable from external apps");
                }
            }
        }
    }
    // Security check to avoid project of invalid fields or lazy projection
    List<String> possibles = getPossibleFieldsForType(type);
    if (possibles == null) {
        throw new SecurityException("You are asking wrong values " + type);
    }
    checkProjection(possibles, projection);
    checkSelection(possibles, selection);

    Cursor c;
    long id;
    switch (type) {
    case ACCOUNTS:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC";
        }
        break;
    case ACCOUNTS_ID:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        qb.appendWhere(SipProfile.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case CALLLOGS:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = CallLog.Calls.DATE + " DESC";
        }
        break;
    case CALLLOGS_ID:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        qb.appendWhere(CallLog.Calls._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case FILTERS:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = Filter.DEFAULT_ORDER;
        }
        break;
    case FILTERS_ID:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        qb.appendWhere(Filter._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case MESSAGES:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        break;
    case MESSAGES_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        qb.appendWhere(SipMessage.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case THREADS:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL,
                SipMessage.FIELD_TO,
                "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN "
                        + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM
                        + " END AS message_ordering",
                SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE,
                "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ,
                //SipMessage.FIELD_READ,
                "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" };
        //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX
        //        + "," + SipMessage.MESSAGE_TYPE_SENT + ")");
        finalGrouping = "message_ordering";
        regUri = SipMessage.MESSAGE_URI;
        break;
    case THREADS_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO,
                SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE,
                SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL };
        qb.appendWhere(MESSAGES_THREAD_SELECTION);
        String from = uri.getLastPathSegment();
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { from, from });
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        synchronized (profilesStatus) {
            ContentValues[] cvs = new ContentValues[profilesStatus.size()];
            int i = 0;
            for (ContentValues ps : profilesStatus.values()) {
                cvs[i] = ps;
                i++;
            }
            c = getCursor(cvs);
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    case ACCOUNTS_STATUS_ID:
        id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            ContentValues cv = profilesStatus.get(id);
            if (cv == null) {
                return null;
            }
            c = getCursor(new ContentValues[] { cv });
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder);

    c.setNotificationUri(getContext().getContentResolver(), regUri);
    return c;
}

From source file:com.odoo.support.provider.OContentProvider.java

private Cursor createQuery(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sort) {//from  w w w. j av  a  2 s.c  om
    reInitModel();
    SQLiteQueryBuilder query = new SQLiteQueryBuilder();
    boolean withAlias = (projection.length < model.projection().length);
    StringBuffer joins = new StringBuffer();
    String base_table = model.getTableName();
    String base_alias = base_table + "_base";
    HashMap<String, String> projectionMap = new HashMap<String, String>();
    List<String> mJoinTables = new ArrayList<String>();
    for (String col_name : projection) {
        String col = col_name;
        if (col_name.contains(".")) {
            col = col_name.split("\\.")[0];
        }
        OColumn column = model.getColumn(col);
        String display_col = col;
        if (withAlias) {
            display_col = base_alias + "." + col + " AS " + col;
            boolean many2oneJoin = col_name.contains(".");
            if (column.getRelationType() != null && many2oneJoin) {
                OModel rel_model = model.createInstance(column.getType());
                String table = rel_model.getTableName();
                String alias = table;
                alias = table + "_self";
                table += " AS " + alias;
                if (!mJoinTables.contains(alias)) {
                    mJoinTables.add(alias);
                    joins.append(" JOIN ");
                    joins.append(table);
                    joins.append(" ON ");
                    joins.append(base_alias + "." + column.getName());
                    joins.append(" = ");
                    joins.append(alias + "." + OColumn.ROW_ID);
                    joins.append(" ");
                }
                String rel_col = col;
                String rel_col_name = "";
                if (col_name.contains(".")) {
                    rel_col += "_" + col_name.split("\\.")[1];
                    rel_col_name = col_name.split("\\.")[1];
                }
                projectionMap.put(rel_col, alias + "." + rel_col_name + " AS " + rel_col);
            }
        }
        projectionMap.put(col, display_col);
    }
    StringBuffer tables = new StringBuffer();
    tables.append(base_table + ((withAlias) ? " AS " + base_alias : " "));
    tables.append(joins.toString());
    query.setTables(tables.toString());
    query.setProjectionMap(projectionMap);
    StringBuffer whr = new StringBuffer();
    String where = null;
    if (selection != null && selectionArgs != null) {
        if (withAlias) {
            // Check for and
            Pattern pattern = Pattern.compile(" and | AND ");
            String[] data = pattern.split(selection);
            StringBuffer or_string = new StringBuffer();
            for (String token : data) {
                if (token.contains("OR") || token.contains("or")) {
                    or_string.append(token.trim());
                    or_string.append(" OR ");
                } else {
                    whr.append(base_alias + "." + token.trim());
                    whr.append(" AND ");
                }
            }
            if (whr.length() > 0)
                whr.delete(whr.length() - 5, whr.length());
            // Check for or
            if (or_string.length() > 0) {
                if (whr.length() > 0)
                    whr.append(" AND ");
                pattern = Pattern.compile(" or | OR ");
                data = pattern.split(or_string.toString());
                for (String token : data) {
                    if (!token.contains(base_alias)) {
                        if (token.contains("(")) {
                            whr.append("(");
                            token = token.replaceAll("\\(", "");
                            whr.append(base_alias + "." + token.trim());
                        } else if (token.contains(")")) {
                            token = token.replaceAll("\\)", "");
                            whr.append(base_alias + "." + token.trim());
                            whr.append(")");
                        } else {
                            whr.append(base_alias + "." + token.trim());
                        }
                    } else {
                        whr.append(token.trim());
                    }
                    whr.append(" OR ");
                }
                if (whr.length() > 0)
                    whr.delete(whr.length() - 4, whr.length());
            }
        } else {
            whr.append(selection);
        }
        where = whr.toString();
    }
    Cursor c = null;
    int uriMatch = matcher.match(uri);
    switch (uriMatch) {
    case SINGLE_ROW:
        // Return a single entry, by ID.
        String id = uri.getLastPathSegment();
        query.appendWhere(base_alias + "." + OColumn.ROW_ID + " = " + id);
    case COLLECTION:
        c = query.query(model.getReadableDatabase(), null, where, selectionArgs, null, null, sort);
        return c;
    default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
}