Example usage for android.content ContentProviderClient update

List of usage examples for android.content ContentProviderClient update

Introduction

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

Prototype

public int update(@NonNull Uri url, @Nullable ContentValues values, @Nullable String selection,
        @Nullable String[] selectionArgs) throws RemoteException 

Source Link

Document

See ContentProvider#update ContentProvider.update

Usage

From source file:saschpe.birthdays.service.CalendarSyncService.java

/**
 * Updates the calendar color//  w ww .j a  v  a 2 s.c  om
 */
public static void updateCalendarColor(Context context) {
    int color = PreferencesHelper.getCalendarColor(context);
    ContentResolver cr = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(getCalendarUri(context, CalendarContract.Calendars.CONTENT_URI),
            getCalendar(context));

    Log.d(TAG, "Updating calendar " + uri.toString() + " color " + color);

    ContentProviderClient client = cr.acquireContentProviderClient(CalendarContract.AUTHORITY);

    ContentValues values = new ContentValues();
    values.put(CalendarContract.Calendars.CALENDAR_COLOR, color);
    try {
        client.update(uri, values, null, null);
    } catch (RemoteException e) {
        Log.e(TAG, "Failed to update calendar color!", e);
    }
    client.release();
}

From source file:fr.free.nrw.commons.contributions.ContributionDao.java

public void save(Contribution contribution) {
    ContentProviderClient db = clientProvider.get();
    try {/* w ww. j av a  2 s . com*/
        if (contribution.getContentUri() == null) {
            contribution.setContentUri(db.insert(BASE_URI, toContentValues(contribution)));
        } else {
            db.update(contribution.getContentUri(), toContentValues(contribution), null, null);
        }
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    } finally {
        db.release();
    }
}

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

private void commit(ContentProviderClient usersProvider, SyncResult syncResult) {
    // commit users table
    Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true")
            .appendQueryParameter(Users.COMMIT, "true").build();
    try {//from   w w  w  . j a  v  a  2  s.c  om
        usersProvider.update(uri, null, null, null);
        Log.d(TAG, "users database committed");
        Contact.invalidate();
    } catch (Exception e) {
        Log.e(TAG, "error committing users database - aborting sync", e);
        syncResult.databaseError = true;
    }
}

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

/**
 * Convert a contact when they become a user and sync remote changes to a followed user.
 *//*from   w w w  .  java 2 s .c  o m*/
private void syncUser(ContentProviderClient cp, Sync<User> sync) throws RemoteException {
    User user = sync.object;
    ContentValues vals = new ContentValues(1);
    switch (sync.action) {
    case INSERT:
        user.localId = Contacts.idForHash(user.emailHash);
        if (user.localId > 0) {
            vals.put(Contacts.GLOBAL_ID, user.globalId);
            cp.update(ContentUris.withAppendedId(CONTACTS_URI, user.localId), vals, null, null);
            cp.insert(SYNCS_URI, Syncs.values(sync));
        }
        break;
    case UPDATE:
        int following = user.isFollowing ? 1 : 0;
        vals.put(Contacts.FOLLOWING, following);
        String sel = Contacts.GLOBAL_ID + " = ? AND " + Contacts.FOLLOWING + " <> ?";
        String[] args = Elements.toStrings(user.globalId, following);
        if (cp.update(CONTACTS_URI, vals, sel, args) > 0 && user.isFollowing) {
            ReviewsService.download(user.globalId);
        }
        break;
    }
}

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

/**
 * Sync remote changes to a review draft.
 *//*from   w  w w  .j  a va2 s .com*/
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:net.sf.diningout.content.SyncAdapter.java

/**
 * Sync remote changes to a review./*  w ww.  j a  v  a  2 s.c  o  m*/
 */
private void syncReview(ContentProviderClient cp, Sync<Review> sync) throws RemoteException {
    Review review = sync.object;
    switch (sync.action) {
    case INSERT:
        ReviewsService.add(review);
        if (review.localId > 0 && review.userId > 0) { // friend's review
            cp.insert(SYNCS_URI, Syncs.values(sync));
        }
        break;
    case UPDATE:
        ContentValues vals = new ContentValues(3);
        vals.put(Reviews.COMMENTS, review.comments);
        vals.put(Reviews.RATING, review.rating);
        vals.put(Reviews.STATUS_ID, review.status.id);
        String sel = Reviews.GLOBAL_ID + " = ?";
        String[] args = { String.valueOf(review.globalId) };
        cp.update(REVIEWS_URI, vals, sel, args);
        break;
    }
    /* update restaurant rating and last visit if own review */
    String id = String.valueOf(Restaurants.idForGlobalId(review.restaurantId));
    if (sync.action != INSERT) { // already called in add
        cr().call(AUTHORITY_URI, CALL_UPDATE_RESTAURANT_RATING, id, null);
    }
    if (review.userId == 0 && sync.action != UPDATE) {
        cr().call(AUTHORITY_URI, CALL_UPDATE_RESTAURANT_LAST_VISIT, id, null);
    }
}

From source file:org.totschnig.myexpenses.sync.SyncAdapter.java

private List<TransactionChange> getLocalChanges(ContentProviderClient provider, long accountId,
        long sequenceNumber) throws RemoteException {
    List<TransactionChange> result = new ArrayList<>();
    Uri changesUri = buildChangesUri(sequenceNumber, accountId);
    boolean hasLocalChanges = hasLocalChanges(provider, changesUri);
    if (hasLocalChanges) {
        ContentValues currentSyncIncrease = new ContentValues(1);
        long nextSequence = sequenceNumber + 1;
        currentSyncIncrease.put(KEY_SYNC_SEQUENCE_LOCAL, nextSequence);
        //in case of failed syncs due to non-available backends, sequence number might already be higher than nextSequence
        //we must take care to not decrease it here
        provider.update(TransactionProvider.ACCOUNTS_URI, currentSyncIncrease,
                KEY_ROWID + " = ? AND " + KEY_SYNC_SEQUENCE_LOCAL + " < ?",
                new String[] { String.valueOf(accountId), String.valueOf(nextSequence) });
    }//  w ww  . j  av  a 2  s.c  o  m
    if (hasLocalChanges) {
        Cursor c = provider.query(changesUri, null, null, null, null);
        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    TransactionChange transactionChange = TransactionChange.create(c);
                    result.add(transactionChange);
                } while (c.moveToNext());
            }
            c.close();
        }
    }
    return result;
}

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

/**
 * Update the synchronised object at the URI with the values received from the server.
 *
 * @param synceds can be null//from  ww  w  . j  av  a 2s .  c om
 */
private void response(List<? extends Synced> synceds, ContentProviderClient cp, Uri uri)
        throws RemoteException {
    if (synceds == null) {
        return;
    }
    ContentValues vals = new ContentValues(2);
    String sel = Columns.VERSION + " = ?";
    String[] args = new String[1];
    int size = synceds.size();
    for (int i = 0; i < size; i++) {
        Synced synced = synceds.get(i);
        if (synced.globalId > 0 && uri != REVIEW_DRAFTS_URI) {
            vals.put(Columns.GLOBAL_ID, synced.globalId);
            if (uri == RESTAURANTS_URI) {
                Restaurants.deleteConflict(synced.localId, synced.globalId);
            }
        }
        vals.put(Columns.DIRTY, synced.dirty);
        args[0] = String.valueOf(synced.version);
        cp.update(ContentUris.withAppendedId(uri, synced.localId), vals, sel, args);
        vals.clear();
    }
}

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

/**
 * The actual sync procedure.//from  w w  w .ja  v a2s.  com
 * This one uses the slowest method ever: it first checks for every phone
 * number in all contacts and it sends them to the server. Once a response
 * is received, it deletes all the raw contacts created by us and then
 * recreates only the ones the server has found a match for.
 */
public void performSync(Context context, Account account, String authority, ContentProviderClient provider,
        ContentProviderClient usersProvider, SyncResult syncResult) throws OperationCanceledException {

    final Map<String, RawPhoneNumberEntry> lookupNumbers = new HashMap<>();
    final List<String> jidList = new ArrayList<>();

    // resync users database
    Log.v(TAG, "resyncing users database");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // update users database
    Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").build();
    try {
        int count = usersProvider.update(uri, new ContentValues(), null, null);
        Log.d(TAG, "users database resynced (" + count + ")");
    } catch (Exception e) {
        Log.e(TAG, "error resyncing users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    // query all contacts
    Cursor cursor;
    try {
        cursor = usersProvider.query(Users.CONTENT_URI_OFFLINE,
                new String[] { Users.JID, Users.NUMBER, Users.LOOKUP_KEY }, null, null, null);
    } catch (Exception e) {
        Log.e(TAG, "error querying users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    while (cursor.moveToNext()) {
        if (mCanceled) {
            cursor.close();
            throw new OperationCanceledException();
        }

        String jid = cursor.getString(0);
        String number = cursor.getString(1);
        String lookupKey = cursor.getString(2);

        // avoid to send duplicates to the server
        if (lookupNumbers.put(XmppStringUtils.parseLocalpart(jid),
                new RawPhoneNumberEntry(lookupKey, number, jid)) == null)
            jidList.add(jid);
    }
    cursor.close();

    if (mCanceled)
        throw new OperationCanceledException();

    // empty contacts :-|
    if (jidList.size() == 0) {
        // delete all Kontalk raw contacts
        try {
            syncResult.stats.numDeletes += deleteAll(account, provider);
        } catch (Exception e) {
            Log.e(TAG, "contact delete error", e);
            syncResult.databaseError = true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            try {
                syncResult.stats.numDeletes += deleteProfile(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "profile delete error", e);
                syncResult.databaseError = true;
            }
        }

        commit(usersProvider, syncResult);
    }

    else {
        final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext);

        // register presence broadcast receiver
        PresenceBroadcastReceiver receiver = new PresenceBroadcastReceiver(jidList, this);
        IntentFilter f = new IntentFilter();
        f.addAction(MessageCenterService.ACTION_PRESENCE);
        f.addAction(MessageCenterService.ACTION_ROSTER_MATCH);
        f.addAction(MessageCenterService.ACTION_PUBLICKEY);
        f.addAction(MessageCenterService.ACTION_BLOCKLIST);
        f.addAction(MessageCenterService.ACTION_LAST_ACTIVITY);
        f.addAction(MessageCenterService.ACTION_CONNECTED);
        lbm.registerReceiver(receiver, f);

        // request current connection status
        MessageCenterService.requestConnectionStatus(mContext);

        // wait for the service to complete its job
        synchronized (this) {
            // wait for connection
            try {
                wait(MAX_WAIT_TIME);
            } catch (InterruptedException e) {
                // simulate canceled operation
                mCanceled = true;
            }
        }

        lbm.unregisterReceiver(receiver);

        // last chance to quit
        if (mCanceled)
            throw new OperationCanceledException();

        List<PresenceItem> res = receiver.getResponse();
        if (res != null) {
            ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
            // TODO operations.size() could be used instead (?)
            int op = 0;

            // this is the time - delete all Kontalk raw contacts
            try {
                syncResult.stats.numDeletes += deleteAll(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "contact delete error", e);
                syncResult.databaseError = true;
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                try {
                    syncResult.stats.numDeletes += deleteProfile(account, provider);
                } catch (Exception e) {
                    Log.e(TAG, "profile delete error", e);
                    syncResult.databaseError = true;
                }
            }

            ContentValues registeredValues = new ContentValues();
            registeredValues.put(Users.REGISTERED, 1);
            for (int i = 0; i < res.size(); i++) {
                PresenceItem entry = res.get(i);
                if (entry.discarded)
                    continue;

                final RawPhoneNumberEntry data = lookupNumbers.get(XmppStringUtils.parseLocalpart(entry.from));
                if (data != null && data.lookupKey != null) {
                    // add contact
                    addContact(account, getDisplayName(provider, data.lookupKey, data.number), data.number,
                            data.jid, operations, op++);
                } else {
                    syncResult.stats.numSkippedEntries++;
                }

                // update fields
                try {
                    String status = entry.status;

                    if (!TextUtils.isEmpty(status))
                        registeredValues.put(Users.STATUS, status);
                    else
                        registeredValues.putNull(Users.STATUS);

                    if (entry.timestamp >= 0)
                        registeredValues.put(Users.LAST_SEEN, entry.timestamp);
                    else
                        registeredValues.putNull(Users.LAST_SEEN);

                    if (entry.publicKey != null) {
                        try {
                            PGPPublicKey pubKey = PGP.getMasterKey(entry.publicKey);
                            // trust our own key blindly
                            int trustLevel = Authenticator.isSelfJID(mContext, entry.from)
                                    ? MyUsers.Keys.TRUST_VERIFIED
                                    : -1;
                            // update keys table immediately
                            Keyring.setKey(mContext, entry.from, entry.publicKey, trustLevel);

                            // no data from system contacts, use name from public key
                            if (data == null) {
                                PGPUserID uid = PGP.parseUserId(pubKey,
                                        XmppStringUtils.parseDomain(entry.from));
                                if (uid != null) {
                                    registeredValues.put(Users.DISPLAY_NAME, uid.getName());
                                }
                            }
                        } catch (Exception e) {
                            Log.w(TAG, "unable to parse public key", e);
                        }
                    } else {
                        // use roster name if no contact data available
                        if (data == null && entry.rosterName != null) {
                            registeredValues.put(Users.DISPLAY_NAME, entry.rosterName);
                        }
                    }

                    // blocked status
                    registeredValues.put(Users.BLOCKED, entry.blocked);
                    // user JID as reported by the server
                    registeredValues.put(Users.JID, entry.from);

                    /*
                     * Since UsersProvider.resync inserted the user row
                     * using our server name, it might have changed because
                     * of what the server reported. We already put into the
                     * values the new JID, but we need to use the old one
                     * in the where condition so we will have a match.
                     */
                    String origJid;
                    if (data != null)
                        origJid = XMPPUtils.createLocalJID(mContext,
                                XmppStringUtils.parseLocalpart(entry.from));
                    else
                        origJid = entry.from;
                    usersProvider.update(Users.CONTENT_URI_OFFLINE, registeredValues, Users.JID + " = ?",
                            new String[] { origJid });

                    // clear data
                    registeredValues.remove(Users.DISPLAY_NAME);

                    // if this is our own contact, trust our own key later
                    if (Authenticator.isSelfJID(mContext, entry.from)) {
                        // register our profile while we're at it
                        if (data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                            // add contact
                            addProfile(account, Authenticator.getDefaultDisplayName(mContext), data.number,
                                    data.jid, operations, op++);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "error updating users database", e);
                    // we shall continue here...
                }
            }

            try {
                if (operations.size() > 0)
                    provider.applyBatch(operations);
                syncResult.stats.numInserts += op;
                syncResult.stats.numEntries += op;
            } catch (Exception e) {
                Log.w(TAG, "contact write error", e);
                syncResult.stats.numSkippedEntries += op;
                /*
                 * We do not consider system contacts failure a fatal error.
                 * This is actually a workaround for systems with disabled permissions or
                 * exotic firmwares. It can also protect against security 3rd party apps or
                 * non-Android platforms, such as Jolla/Alien Dalvik.
                 */
            }

            commit(usersProvider, syncResult);
        }

        // timeout or error
        else {
            Log.w(TAG, "connection timeout - aborting sync");

            syncResult.stats.numIoExceptions++;
        }
    }
}

From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java

private void syncCheckins(ContentProviderClient provider, String cookie) {
    Cursor cursor = null;//from w w w .j  av  a2s. c  o  m
    try {
        cursor = provider.query(Table.ATTENDEE.getBaseUri(),
                new String[] { Table.Attendee.ID, Table.Attendee.CHECKIN, Table.Attendee.EVENT_ID, },
                Table.Attendee.CHECKIN_MODIFIED, null, null);
        if (0 == cursor.getCount()) {
            Log.d(TAG, "No checkin to sync.");
            return;
        }
        int syncCount = 0;
        while (cursor.moveToNext()) {
            String attendeeId = cursor.getString(cursor.getColumnIndexOrThrow(Table.Attendee.ID));
            String eventId = cursor.getString(cursor.getColumnIndexOrThrow(Table.Attendee.EVENT_ID));
            long checkin = cursor.getLong(cursor.getColumnIndexOrThrow(Table.Attendee.CHECKIN));
            long serverCheckin = postCheckIn(attendeeId, eventId, checkin == 0, cookie);
            if (serverCheckin >= 0) {
                ContentValues values = new ContentValues();
                values.put(Table.Attendee.CHECKIN_MODIFIED, false);
                if (0 == serverCheckin) {
                    values.putNull(Table.Attendee.CHECKIN);
                } else {
                    values.put(Table.Attendee.CHECKIN, serverCheckin);
                }
                provider.update(Table.ATTENDEE.getItemUri(eventId, attendeeId), values, null, null);
                ++syncCount;
            }
        }
        Log.d(TAG, syncCount + " checkin(s) synced.");
    } catch (RemoteException e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}