Example usage for android.content ContentProviderClient query

List of usage examples for android.content ContentProviderClient query

Introduction

In this page you can find the example usage for android.content ContentProviderClient query.

Prototype

public @Nullable Cursor query(@NonNull Uri url, @Nullable String[] projection, @Nullable String selection,
        @Nullable String[] selectionArgs, @Nullable String sortOrder) throws RemoteException 

Source Link

Document

See ContentProvider#query ContentProvider.query

Usage

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

/**
 * We know that the group exists locally, so we can use the data in the JSON group as gold
 * @param group/*from  w  w  w.  j  a  v  a2  s  .c o  m*/
 * @param provider
 * @param authToken
 * @param account
 * @param syncResult
 * @throws JSONException
 * @throws RemoteException
 * @throws OperationApplicationException
 */
private void optimisticallyAddContactsToExistingGroup(JSONObject group, ContentProviderClient provider,
        String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException {

    if (!group.has(JSONKeys.KEY_MEMBERS)) {
        return;
    }
    String groupCloudId = group.getString(JSONKeys.KEY_ID);
    Cursor groupCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID, GMSGroup.CLOUD_ID },
            GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }, null);
    try {
        if (groupCursor == null || 1 != groupCursor.getCount() || !groupCursor.moveToFirst()) {
            syncResult.databaseError = true;
            return;
        }
        long groupId = groupCursor.getLong(0);
        if (groupId < 0L) {
            syncResult.databaseError = true;
            return;
        }
        // Optimistically add the contacts
        JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS);
        for (int j = 0; j < membersArray.length(); ++j) {
            JSONObject member = membersArray.getJSONObject(j);
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // If the first operation asserts it means the contact exists already
            // Operation 0
            ContentProviderOperation op = ContentProviderOperation.newAssertQuery(GMSContacts.CONTENT_URI)
                    .withSelection(GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) })
                    .withExpectedCount(0).build();
            ops.add(op);
            op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI)
                    .withValues(GMSApplication.getMemberValues(member)).withValue(GMSContact.GROUP_ID, groupId)
                    .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).build();
            ops.add(op);
            try {
                @SuppressWarnings("unused")
                ContentProviderResult[] results = provider.applyBatch(ops);
            } catch (OperationApplicationException e) {
                // The contact already exists, so we'll optionally update it, based on its version
                Cursor contactCursor = null;
                try {
                    contactCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.GROUP_ID },
                            GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) }, null);
                    if (contactCursor == null || !contactCursor.moveToFirst()) {
                        syncResult.databaseError = true;
                        return;
                    }
                    // The member already exists, so optinally update it
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists. If its the right version, we don't need to do the update
                    // So we assert that we'll find zero records with the current version and if that's right, we'll update our
                    // record, including the version with the new record data
                    op = ContentProviderOperation
                            .newAssertQuery(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withSelection(GMSContact.VERSION + "=?",
                                    new String[] { member.getString(JSONKeys.KEY_VERSION) })
                            .withExpectedCount(0).build();
                    ops.add(op);
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValues(GMSApplication.getMemberValues(member))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    provider.applyBatch(ops);
                } catch (OperationApplicationException l) {
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists and is of the current version, so no update of attributes is needed
                    // We still have to update the status to SYNCED so we don't blow it away later.
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    try {
                        provider.applyBatch(ops);
                    } catch (OperationApplicationException e1) {
                        syncResult.stats.numSkippedEntries++;
                        e1.printStackTrace();
                    }
                } finally {
                    if (contactCursor != null) {
                        contactCursor.close();
                    }
                }
            }
        }
    } finally {
        if (groupCursor != null) {
            groupCursor.close();
        }
    }
}

From source file:org.kontalk.sync.Syncer.java

private String getDisplayName(ContentProviderClient client, String lookupKey, String defaultValue) {
    String displayName = null;/*from   w  ww. j  a  v a 2s  .  c o m*/
    Cursor nameQuery = null;
    try {
        nameQuery = client.query(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey),
                new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null);
        if (nameQuery.moveToFirst())
            displayName = nameQuery.getString(0);
    } catch (Exception e) {
        // ignored
    } finally {
        // close cursor
        try {
            nameQuery.close();
        } catch (Exception ignored) {
        }
    }

    return (displayName != null) ? displayName : defaultValue;
}

From source file:net.sf.diningout.content.SyncAdapter.java

/**
 * Upload contact changes to the server.
 *//*from ww w . j  a v  a2s.co  m*/
private void uploadContacts(Context context, ContentProviderClient cp) throws RemoteException {
    String[] proj = { _ID, Contacts.GLOBAL_ID, Contacts.EMAIL_HASH, Contacts.FOLLOWING, Contacts.STATUS_ID,
            Contacts.DIRTY, Contacts.VERSION };
    String sel = Contacts.DIRTY + " = 1";
    List<User> users = Contacts.from(cp.query(CONTACTS_URI, proj, sel, null, null));
    if (users != null) {
        LocalBroadcastManager bm = LocalBroadcastManager.getInstance(context);
        bm.sendBroadcast(new Intent(ACTION_CONTACTS_SYNCING));
        response(Server.syncContacts(users), cp, CONTACTS_URI);
        bm.sendBroadcast(new Intent(ACTION_CONTACTS_SYNCED));
    }
}

From source file:com.example.jumpnote.android.SyncAdapter.java

public void reconcileSyncedNotes(ContentProviderClient provider, Account account,
        List<ModelJava.Note> changedNotes, SyncStats syncStats)
        throws RemoteException, OperationApplicationException {
    Cursor noteCursor;/*from  w w  w .  j  a v a2  s  .  c  o  m*/
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
    for (ModelJava.Note changedNote : changedNotes) {
        Uri noteUri = null;

        if (changedNote.getId() != null) {
            noteUri = addCallerIsSyncAdapterParameter(
                    JumpNoteContract.buildNoteUri(account.name, Long.parseLong(changedNote.getId())));
        } else {
            noteCursor = provider.query(JumpNoteContract.buildNoteListUri(account.name), PROJECTION,
                    JumpNoteContract.Notes.SERVER_ID + " = ?", new String[] { changedNote.getServerId() },
                    null);

            if (noteCursor.moveToNext()) {
                noteUri = addCallerIsSyncAdapterParameter(
                        JumpNoteContract.buildNoteUri(account.name, noteCursor.getLong(0)));
            }

            noteCursor.close();
        }

        if (changedNote.isPendingDelete()) {
            // Handle server-side delete.
            if (noteUri != null) {
                operations.add(ContentProviderOperation.newDelete(noteUri).build());
                syncStats.numDeletes++;
            }
        } else {
            ContentValues values = changedNote.toContentValues();
            if (noteUri != null) {
                // Handle server-side update.
                operations.add(ContentProviderOperation.newUpdate(noteUri).withValues(values).build());
                syncStats.numUpdates++;
            } else {
                // Handle server-side insert.
                operations
                        .add(ContentProviderOperation
                                .newInsert(addCallerIsSyncAdapterParameter(
                                        JumpNoteContract.buildNoteListUri(account.name)))
                                .withValues(values).build());
                syncStats.numInserts++;
            }
        }
    }

    provider.applyBatch(operations);
}

From source file:net.sf.diningout.content.SyncAdapter.java

/**
 * Sync remote changes to a review draft.
 *//*from   w ww. j av  a2 s. c om*/
private void syncReviewDraft(ContentProviderClient cp, Sync<Review> sync) throws RemoteException {
    ContentValues vals = ReviewDrafts.values(sync.object);
    /* get current version and increment it */
    Uri uri = ContentUris.withAppendedId(REVIEW_DRAFTS_URI, vals.getAsLong(ReviewDrafts.RESTAURANT_ID));
    String[] proj = { ReviewDrafts.VERSION };
    long version = Cursors.firstLong(cp.query(uri, proj, null, null, null));
    if (version >= 0) {
        vals.put(ReviewDrafts.VERSION, version + 1);
        cp.update(uri, vals, null, null);
    } else {
        cp.insert(REVIEW_DRAFTS_URI, vals);
    }
}

From source file:com.samsung.android.remindme.SyncAdapter.java

public void reconcileSyncedAlerts(ContentProviderClient provider, Account account,
        List<ModelJava.Alert> changedAlerts, SyncStats syncStats)
        throws RemoteException, OperationApplicationException {
    Cursor alertCursor;/*from  w w w. j ava  2s .  c om*/
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
    for (ModelJava.Alert changedAlert : changedAlerts) {
        Uri alertUri = null;

        if (changedAlert.getId() != null) {
            alertUri = addCallerIsSyncAdapterParameter(
                    RemindMeContract.buildAlertUri(account.name, Long.parseLong(changedAlert.getId())));
        } else {
            alertCursor = provider.query(RemindMeContract.buildAlertListUri(account.name), PROJECTION,
                    RemindMeContract.Alerts.SERVER_ID + " = ?", new String[] { changedAlert.getServerId() },
                    null);

            if (alertCursor.moveToNext()) {
                alertUri = addCallerIsSyncAdapterParameter(
                        RemindMeContract.buildAlertUri(account.name, alertCursor.getLong(0)));
            }

            alertCursor.close();
        }

        if (changedAlert.isPendingDelete()) {
            // Handle server-side delete.
            if (alertUri != null) {
                operations.add(ContentProviderOperation.newDelete(alertUri).build());
                syncStats.numDeletes++;
            }
        } else {
            ContentValues values = changedAlert.toContentValues();
            if (alertUri != null) {
                // Handle server-side update.
                operations.add(ContentProviderOperation.newUpdate(alertUri).withValues(values).build());
                syncStats.numUpdates++;
            } else {
                // Handle server-side insert.
                operations
                        .add(ContentProviderOperation
                                .newInsert(addCallerIsSyncAdapterParameter(
                                        RemindMeContract.buildAlertListUri(account.name)))
                                .withValues(values).build());
                syncStats.numInserts++;
            }
        }
    }

    provider.applyBatch(operations);
}

From source file:net.sf.diningout.content.SyncAdapter.java

/**
 * Upload restaurant changes to the server.
 *//*from w w  w.j a  v  a 2  s . c  om*/
private void uploadRestaurants(ContentProviderClient cp) throws RemoteException {
    String[] proj = { _ID, Restaurants.GLOBAL_ID, Restaurants.PLACE_ID, Restaurants.NAME, Restaurants.ADDRESS,
            Restaurants.INTL_PHONE, Restaurants.URL, Restaurants.NOTES, Restaurants.GEOFENCE_NOTIFICATIONS,
            Restaurants.STATUS_ID, Restaurants.DIRTY, Restaurants.VERSION };
    String sel = Restaurants.DIRTY + " = 1";
    List<Restaurant> restaurants = Restaurants.from(cp.query(RESTAURANTS_URI, proj, sel, null, null));
    if (restaurants != null) {
        response(Server.syncRestaurants(restaurants), cp, RESTAURANTS_URI);
    }
}

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

private void deleteUnsyncedItems(ContentProviderClient provider, Account account, SyncResult syncResult)
        throws RemoteException, JSONException {

    Log.d(TAG, "Delete unsynced items before count: " + syncResult.stats.numDeletes);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation op;//from w ww. j  a v  a2s  .  c  o  m
    ContentProviderResult[] results;

    // This is the good part
    Cursor unsyncedGroupsCursor = null;
    try {
        final String SELECT = GMSGroup.STATUS + " ISNULL OR " + GMSGroup.STATUS + " != "
                + GMSGroup.STATUS_SYNCED;
        unsyncedGroupsCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID,
                GMSGroup.CLOUD_ID, GMSGroup.STATUS, GMSGroup.NAME, GMSGroup.RAW_CONTACT_ID }, SELECT, null,
                null);
        ContentProviderClient contactsProvider;
        if (unsyncedGroupsCursor.moveToFirst()) {
            contactsProvider = getContext().getContentResolver()
                    .acquireContentProviderClient(ContactsContract.AUTHORITY);
            do {
                long groupId = unsyncedGroupsCursor.getLong(0);
                long groupRawContactId = unsyncedGroupsCursor.getLong(4);
                Cursor memberCursor = null;
                try {
                    memberCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.GROUP_ID }, GMSContact.GROUP_ID + "=?",
                            new String[] { String.valueOf(groupId) }, null);
                    while (memberCursor.moveToNext()) {
                        op = ContentProviderOperation.newDelete(
                                ContentUris.withAppendedId(GMSContacts.CONTENT_URI, memberCursor.getLong(0)))
                                .build();
                        ops.add(op);
                    }
                } finally {
                    if (memberCursor != null) {
                        memberCursor.close();
                    }
                }
                op = ContentProviderOperation
                        .newDelete(ContentUris.withAppendedId(GMSGroups.CONTENT_URI, groupId)).build();
                ops.add(op);
                if (groupRawContactId <= 0) {
                    Cursor accountContactsCursor = null;
                    try {
                        String sourceId = unsyncedGroupsCursor.getString(1);
                        Log.d(TAG, String.format("Unsynced Group Id: %1$d, SourceId: %2$s", groupId, sourceId));
                        accountContactsCursor = GMSContactOperations.findGroupInContacts(contactsProvider,
                                account, sourceId);
                        if (accountContactsCursor != null && accountContactsCursor.moveToFirst()) {
                            groupRawContactId = accountContactsCursor.getLong(0);
                        }
                    } finally {
                        if (accountContactsCursor != null) {
                            accountContactsCursor.close();
                        }
                    }
                    GMSContactOperations.removeGroupFromContacts(contactsProvider, account, groupRawContactId,
                            syncResult);
                }
            } while (unsyncedGroupsCursor.moveToNext());
        }
    } finally {
        if (unsyncedGroupsCursor != null) {
            unsyncedGroupsCursor.close();
        }
    }
    // Now delete any unsynced contacts from the local provider
    op = ContentProviderOperation.newDelete(GMSContacts.CONTENT_URI)
            .withSelection(
                    GMSContact.STATUS + " ISNULL OR " + GMSContact.STATUS + " != " + GMSContact.STATUS_SYNCED,
                    null)
            .build();
    ops.add(op);

    op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI).withValue(GMSGroup.STATUS, null).build();
    ops.add(op);

    op = ContentProviderOperation.newUpdate(GMSContacts.CONTENT_URI).withValue(GMSContact.STATUS, null).build();
    ops.add(op);
    try {
        results = provider.applyBatch(ops);
        int numResults = results.length;
        for (int i = 0; i < numResults; ++i) {
            // The first first N-2 results were deletes
            if (i < numResults - 2) {
                syncResult.stats.numDeletes += results[i].count;
            } else {
                // The last two results were updates
                syncResult.stats.numEntries += results[i].count;
            }
        }
        Log.d(TAG, String.format("Delete unsynced items after count: %1$d, entries: %2$d",
                syncResult.stats.numDeletes, syncResult.stats.numEntries));
    } catch (OperationApplicationException e) {
        syncResult.stats.numSkippedEntries++;
        e.printStackTrace();
    }
}

From source file:net.sf.diningout.content.SyncAdapter.java

/**
 * Upload review draft changes to the server.
 *//*  w w  w . j a  v a  2  s  .com*/
private void uploadReviewDrafts(ContentProviderClient cp) throws RemoteException {
    String[] proj = { ReviewDrafts.RESTAURANT_ID + " AS " + _ID,
            Restaurants.GLOBAL_ID + " AS " + ReviewDrafts.RESTAURANT_ID, ReviewDrafts.COMMENTS,
            alias(ReviewDraftsJoinRestaurants.REVIEW_DRAFT_RATING),
            alias(ReviewDraftsJoinRestaurants.REVIEW_DRAFT_STATUS_ID),
            alias(ReviewDraftsJoinRestaurants.REVIEW_DRAFT_DIRTY),
            alias(ReviewDraftsJoinRestaurants.REVIEW_DRAFT_VERSION) };
    String sel = ReviewDraftsJoinRestaurants.REVIEW_DRAFT_DIRTY + " = 1";
    List<Review> drafts = Reviews
            .from(cp.query(ReviewDraftsJoinRestaurants.CONTENT_URI, proj, sel, null, null));
    if (drafts != null) {
        response(Server.syncReviewDrafts(drafts), cp, REVIEW_DRAFTS_URI);
    }
}

From source file:net.sf.diningout.content.SyncAdapter.java

/**
 * Upload review changes to the server./*from w  w w .j  a v  a  2s  . c o m*/
 */
private void uploadReviews(ContentProviderClient cp) throws RemoteException {
    String[] proj = { alias(ReviewsJoinRestaurants.REVIEW__ID), alias(ReviewsJoinRestaurants.REVIEW_GLOBAL_ID),
            ReviewsJoinRestaurants.RESTAURANT_GLOBAL_ID + " AS " + Reviews.RESTAURANT_ID, Reviews.COMMENTS,
            alias(ReviewsJoinRestaurants.REVIEW_RATING), Reviews.WRITTEN_ON,
            alias(ReviewsJoinRestaurants.REVIEW_STATUS_ID), alias(ReviewsJoinRestaurants.REVIEW_DIRTY),
            alias(ReviewsJoinRestaurants.REVIEW_VERSION) };
    String sel = Reviews.TYPE_ID + " = ? AND " + ReviewsJoinRestaurants.REVIEW_DIRTY + " = 1";
    String[] args = { String.valueOf(PRIVATE.id) };
    List<Review> reviews = Reviews.from(cp.query(ReviewsJoinRestaurants.CONTENT_URI, proj, sel, args, null));
    if (reviews != null) {
        response(Server.syncReviews(reviews), cp, REVIEWS_URI);
    }
}