List of usage examples for android.content ContentProviderClient update
public int update(@NonNull Uri url, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) throws RemoteException
From source file:net.sf.diningout.content.SyncAdapter.java
/** * Sync remote changes to a restaurant.//from w w w . j a v a2 s.c o m */ private void syncRestaurant(ContentProviderClient cp, Sync<Restaurant> sync) throws RemoteException { Restaurant restaurant = sync.object; switch (sync.action) { case INSERT: ContentValues vals = Restaurants.values(restaurant); vals.put(Restaurants.COLOR, Restaurants.defaultColor()); restaurant.localId = ContentUris.parseId(cp.insert(RESTAURANTS_URI, vals)); if (restaurant.localId > 0 && restaurant.status == ACTIVE) { RestaurantService.download(restaurant.localId); try { RestaurantService.photo(restaurant.localId, vals); } catch (IOException e) { Log.e(TAG, "downloading Street View image", e); exception(e); } } break; case UPDATE: restaurant.localId = Restaurants.idForGlobalId(restaurant.globalId); if (restaurant.localId > 0) { vals = Restaurants.values(restaurant); try { // while place_id has UNIQUE constraint cp.update(ContentUris.withAppendedId(RESTAURANTS_URI, restaurant.localId), vals, null, null); } catch (SQLiteConstraintException e) { Log.e(TAG, "updating restaurant from sync", e); exception(e); } try { RestaurantService.photo(restaurant.localId, vals); } catch (IOException e) { Log.e(TAG, "downloading Street View image", e); exception(e); } } else { // re-added on other device sync.action = INSERT; syncRestaurant(cp, sync); } break; } }
From source file:com.taxicop.sync.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/*from ww w . j av a 2 s.c om*/ USER = queryUser(provider); Log.i(TAG, "onPerformSync: Start"); NetworkUtilities.reset(); FROM = queryLastId(provider); Log.d(TAG, "data from= " + FROM); ArrayList<Complaint> queries = query(provider, FROM); NetworkUtilities.add(USER); for (Complaint c : queries) { NetworkUtilities.add(c.RANKING, c.CAR_PLATE, c.DESCRIPTION, c.USER, c.DATE); } Log.d(TAG, "from= " + FROM + " size del query= " + queries.size()); String response = null; if (NetworkUtilities.adapter.size() > 0) { response = ":" + NetworkUtilities.process_upload(); Log.i(TAG, "response: " + response); } else Log.i(TAG, "no data"); if (USER != null) { NetworkUtilities.reset(); NetworkUtilities.add(USER); NetworkUtilities.add(FROM); response = null; if (NetworkUtilities.adapter.size() > 0) { response = NetworkUtilities.process_download(); Log.d(TAG, "" + response); } else Log.e(TAG, "no data"); try { if (response != null) { final JSONArray cars = new JSONArray(response); provider.delete(PlateContentProvider.URI_REPORT, null, null); Log.i(TAG, "" + response); for (int i = 0; i < cars.length(); i++) { JSONObject COMPLETE = cars.getJSONObject(i); JSONObject e1 = COMPLETE.getJSONObject("fields"); float rank = (float) e1.getDouble(Fields.RANKING); String car = e1.getString(Fields.CAR_PLATE); String desc = e1.getString(Fields.DESCRIPTION); String date = e1.getString(Fields.DATE_REPORT); ContentValues in = new ContentValues(); in.put(Fields.ID_KEY, i); in.put(Fields.CAR_PLATE, car); in.put(Fields.RANKING, rank); in.put(Fields.DATE_REPORT, date); in.put(Fields.DESCRIPTION, desc); insert.add(in); } Log.d(TAG, "current ammount to insert= " + insert.size() + ", FROM=" + FROM); ContentValues upd = new ContentValues(); upd.put(Fields.ITH, insert.size()); upd.put(Fields.ID_USR, USER); provider.update(PlateContentProvider.URI_USERS, upd, "" + Fields.ID_USR + " = '" + USER + "'", null); //if(insert.size()>FROM) provider.applyBatch(insertData()); insert.clear(); } else { Log.e(TAG, "null response"); } } catch (Exception e) { Log.e(TAG, "inserting .... fucked => message: " + e.getMessage()); } } }
From source file:net.sf.diningout.content.SyncAdapter.java
/** * Insert new system contacts, delete orphaned app contacts, and synchronise any changes to * existing./* w w w . j a v a 2 s.c o m*/ */ private void refreshContacts(Context context, ContentProviderClient cp) throws RemoteException { /* get system contacts */ String[] proj = { Email.ADDRESS, ContactsContract.Contacts.LOOKUP_KEY, RawContacts.CONTACT_ID, ContactsContract.Contacts.DISPLAY_NAME }; String sel = Email.IN_VISIBLE_GROUP + " = 1 AND " + Email.ADDRESS + " <> ?"; String[] args = { Accounts.selected().name }; EasyCursor sys = new EasyCursor(cr().query(Email.CONTENT_URI, proj, sel, args, Email.ADDRESS)); /* get app contacts */ proj = new String[] { Contacts.EMAIL, Contacts.ANDROID_LOOKUP_KEY, Contacts.ANDROID_ID, Contacts.NAME, _ID, Contacts.FOLLOWING, Contacts.STATUS_ID }; sel = Contacts.EMAIL + " IS NOT NULL"; EasyCursor app = new EasyCursor(cp.query(CONTACTS_URI, proj, sel, null, Contacts.EMAIL)); /* compare and sync */ ContentValues vals = new ContentValues(); for (CursorJoiner.Result result : new CursorJoiner(sys, new String[] { Email.ADDRESS }, app, new String[] { Contacts.EMAIL })) { switch (result) { case LEFT: // new system contact, insert into app contacts String email = sys.getString(Email.ADDRESS); String hash = BaseEncoding.base64() .encode(Hashing.sha512().hashString(email.toLowerCase(ENGLISH), UTF_8).asBytes()); long id = Contacts.idForHash(hash); // do we have this contact and not know it? /* insert or update values */ vals.put(Contacts.ANDROID_LOOKUP_KEY, sys.getString(ContactsContract.Contacts.LOOKUP_KEY)); vals.put(Contacts.ANDROID_ID, sys.getLong(RawContacts.CONTACT_ID)); String name = sys.getString(ContactsContract.Contacts.DISPLAY_NAME); vals.put(Contacts.NAME, name); vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(name)); vals.put(Contacts.EMAIL, email); if (id <= 0) { vals.put(Contacts.EMAIL_HASH, hash); vals.put(Contacts.COLOR, Contacts.defaultColor()); id = ContentUris.parseId(cp.insert(CONTACTS_URI, vals)); } else { cp.update(ContentUris.withAppendedId(CONTACTS_URI, id), vals, null, null); } if (id > 0) { context.startService(new Intent(context, FriendColorService.class) .putExtra(FriendColorService.EXTRA_ID, id)); } break; case RIGHT: // orphaned app contact, delete unless user is following if (app.getInt(Contacts.FOLLOWING) == 0 && app.getInt(Contacts.STATUS_ID) == ACTIVE.id) { vals.put(Contacts.STATUS_ID, DELETED.id); vals.put(Contacts.DIRTY, 1); cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null); } break; case BOTH: // matching contacts, update details in app if needed String s = sys.getString(ContactsContract.Contacts.LOOKUP_KEY); if (!s.equals(app.getString(Contacts.ANDROID_LOOKUP_KEY))) { vals.put(Contacts.ANDROID_LOOKUP_KEY, s); } long l = sys.getLong(RawContacts.CONTACT_ID); if (l != app.getLong(Contacts.ANDROID_ID)) { vals.put(Contacts.ANDROID_ID, l); } s = sys.getString(ContactsContract.Contacts.DISPLAY_NAME); if (!s.equals(app.getString(Contacts.NAME))) { vals.put(Contacts.NAME, s); vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(s)); } if (app.getInt(Contacts.STATUS_ID) == DELETED.id) { vals.put(Contacts.STATUS_ID, ACTIVE.id); vals.put(Contacts.DIRTY, 1); } if (vals.size() > 0) { cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null); context.startService(new Intent(context, FriendColorService.class) .putExtra(FriendColorService.EXTRA_ID, app.getLong(_ID))); } break; } vals.clear(); } sys.close(); app.close(); }
From source file:info.dc585.hpt.sa.SyncAdapter.java
private void syncTopHackers(ContentProviderClient provider, SyncResult syncResult) { try {/* w w w.j a v a2 s . c o m*/ Log.d(TAG, "Calling something to sync up hackerpoint db"); JSONArray hackers = NetworkUtilities.getTopHackers(); if (hackers == null) { Log.e(TAG, "somehow got null hackers, explode please"); syncResult.stats.numParseExceptions++; } if (hackers.length() == 0) { return; } Log.i(TAG, "Updateing content provider"); Log.i(TAG, "hackers.length():" + hackers.length()); for (int i = 0; i < hackers.length(); i++) { JSONObject jo = hackers.getJSONObject(i); String name = jo.getString("name"); String selection = TopHackerTable.COLUMN_NAME + " like ?"; String[] selectionArgs = { name }; String[] projection = { TopHackerTable.COLUMN_ID, TopHackerTable.COLUMN_NAME }; ContentValues values = new ContentValues(); // FIXME: Dear self, WTF would i trust network returned data without verifying limits ;) // TODO: See FIXME above. Cursor c = provider.query(HackerPointsContentProvider.HACKERS_URI, projection, selection, selectionArgs, null); if (c.getCount() == 0) { Log.d(TAG, "performing insert for new name:" + name); int points = jo.getInt("points"); values.put(TopHackerTable.COLUMN_POINTS, points); int pool = jo.getInt("pool"); values.put(TopHackerTable.COLUMN_POOL, pool); int internets = jo.getInt("internets"); values.put(TopHackerTable.COLUMN_INTERNETS, internets); String pictureURL = jo.getString("pictureURL"); values.put(TopHackerTable.COLUMN_PICTUREURL, pictureURL); values.put(TopHackerTable.COLUMN_NAME, name); values.put(TopHackerTable.COLUMN_UPDATE, System.currentTimeMillis()); provider.insert(HackerPointsContentProvider.HACKERS_URI, values); syncResult.stats.numInserts++; } else if (c.getCount() == 1) { Log.d(TAG, "performing update for name:" + name); if (name == null || name.isEmpty()) { Log.e(TAG, "null or empty name"); continue; } int points = jo.getInt("points"); values.put(TopHackerTable.COLUMN_POINTS, points); int pool = jo.getInt("pool"); values.put(TopHackerTable.COLUMN_POOL, pool); int internets = jo.getInt("internets"); values.put(TopHackerTable.COLUMN_INTERNETS, internets); String pictureURL = jo.getString("pictureURL"); values.put(TopHackerTable.COLUMN_PICTUREURL, pictureURL); int rows = provider.update(HackerPointsContentProvider.HACKERS_URI, values, selection, selectionArgs); Log.d(TAG, "Updated:" + rows + ": rows"); syncResult.stats.numUpdates += rows; } else { Log.e(TAG, "Cursor count was not 0 or 1 was:" + c.getCount()); continue; } } // Now run through both lists and figure out which one to delete. String[] projection = { TopHackerTable.COLUMN_NAME }; Cursor c = provider.query(HackerPointsContentProvider.HACKERS_URI, projection, null, null, null); if (c.getCount() == 0) { return; } ArrayList<String> goodNames = new ArrayList<String>(); ArrayList<String> rmNames = new ArrayList<String>(); for (int i = 0; i < hackers.length(); i++) { JSONObject jo = hackers.getJSONObject(i); String name = jo.getString("name"); goodNames.add(name); } while (c.moveToNext()) { int namec = c.getColumnIndex(TopHackerTable.COLUMN_NAME); String dbName = c.getString(namec); if (goodNames.contains(dbName) == false) { Log.d(TAG, "Adding name:" + dbName + ": to the delete list"); rmNames.add(dbName); } } for (String nextName : rmNames) { Log.d(TAG, "deleting name:" + nextName + ":"); // FIXME: use column name from Table class String where = " name = ? "; String[] whereArgs = { nextName }; int rows = provider.delete(HackerPointsContentProvider.HACKERS_URI, where, whereArgs); syncResult.stats.numDeletes += rows; } } catch (final AuthenticationException e) { Log.e(TAG, "AuthenticationException", e); } catch (final JSONException e) { Log.e(TAG, "JSONException", e); } catch (final IOException e) { Log.e(TAG, "IOException", e); } catch (final ParseException e) { Log.e(TAG, "ParseException", e); syncResult.stats.numParseExceptions++; } catch (final RemoteException e) { Log.e(TAG, "RemoteException", e); } }
From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java
private ContentProviderResult[] optimisticallyCreateGroupAndContacts(JSONObject group, ContentProviderClient provider, ContentProviderClient contactsProvider, String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException, OperationApplicationException { String groupCloudId = group.getString(JSONKeys.KEY_ID); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // If the first operation asserts, that means the group already exists // Operation 0 ContentProviderOperation.Builder op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI) .withValue(GMSGroup._ID, "").withValue(GMSGroup.CLOUD_ID, "") .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withExpectedCount(0); ops.add(op.build());//from www . ja v a 2s . com // If we get this far, create the group from the information the JSON object // Operation 1 ContentValues groupValues = GMSApplication.getGroupValues(group); op = ContentProviderOperation.newInsert(GMSGroups.CONTENT_URI).withValues(groupValues) .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED); ops.add(op.build()); // And add the contacts // Operations 2 - N + 2 where N is the number of members in group if (group.has(JSONKeys.KEY_MEMBERS)) { JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS); int numMembers = membersArray.length(); for (int j = 0; j < numMembers; ++j) { JSONObject member = membersArray.getJSONObject(j); ContentValues memberValues = GMSApplication.getMemberValues(member); op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI).withValues(memberValues) .withValueBackReference(GMSContact.GROUP_ID, 1) .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED); ops.add(op.build()); } } ContentProviderResult[] results = provider.applyBatch(ops); // Create the contact on the device Uri groupUri = results[1].uri; if (groupUri != null) { Cursor cursor = null; try { cursor = GMSContactOperations.findGroupInContacts(contactsProvider, account, groupCloudId); if (cursor.getCount() > 0) { Assert.assertTrue(cursor.moveToFirst()); long oldContactId = cursor.getLong(0); GMSContactOperations.removeGroupFromContacts(contactsProvider, account, oldContactId, syncResult); } long contactId = GMSContactOperations.addGroupToContacts(getContext(), contactsProvider, account, group, syncResult); if (contactId > 0) { ContentValues values = new ContentValues(); values.put(GMSGroup.RAW_CONTACT_ID, contactId); provider.update(groupUri, values, null, null); addNewGroupNotification(group); } } finally { if (cursor != null) { cursor.close(); } } } return results; }
From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java
/** * Uploads any unpublished casts.//from w w w .j ava 2s. com * * This is the method that does all the hard work. * * @param toSync * @param provider * @param syncMap * @param syncResult * @return the number of casts uploaded. * @throws JSONException * @throws NetworkProtocolException * @throws IOException * @throws NoPublicPath * @throws RemoteException * @throws OperationApplicationException * @throws SyncException * @throws InterruptedException */ private int uploadUnpublished(Uri toSync, Account account, ContentProviderClient provider, SyncMap syncMap, HashMap<String, SyncEngine.SyncStatus> syncStatuses, SyncResult syncResult) throws JSONException, NetworkProtocolException, IOException, NoPublicPath, RemoteException, OperationApplicationException, SyncException, InterruptedException { int count = 0; final String type = provider.getType(toSync); final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR); final Cursor uploadMe = provider.query(toSync, null, SELECTION_UNPUBLISHED, null, null); if (uploadMe == null) { throw new SyncException("could not query " + toSync); } final int idCol = uploadMe.getColumnIndex(JsonSyncableItem._ID); try { for (uploadMe.moveToFirst(); !uploadMe.isAfterLast(); uploadMe.moveToNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } final long id = uploadMe.getLong(idCol); final Uri localUri = isDir ? ContentUris.withAppendedId(toSync, id) : toSync; final String postUri = MediaProvider.getPostPath(mContext, localUri); Intent intent = new Intent(SYNC_STATUS_CHANGED); intent.putExtra(EXTRA_SYNC_STATUS, "castBegin"); intent.putExtra(EXTRA_SYNC_ID, id); mContext.sendStickyBroadcast(intent); try { final JSONObject jo = JsonSyncableItem.toJSON(mContext, localUri, uploadMe, syncMap); if (DEBUG) { Log.d(TAG, "uploading " + localUri + " to " + postUri); } // Upload! Any non-successful responses are handled by // exceptions. final HttpResponse res = mNetworkClient.post(postUri, jo.toString()); long serverTime; try { serverTime = getServerTime(res); // We should never get a corrupted date from the server, // but if it does happen, // using the local time is a sane fallback. } catch (final DateParseException e) { serverTime = System.currentTimeMillis(); } // newly-created items return the JSON serialization of the // object as the server // knows it, so the local database needs to be updated to // reflect that. final JSONObject newJo = NetworkClient.toJsonObject(res); try { final SyncStatus ss = loadItemFromJsonObject(newJo, syncMap, serverTime); // update immediately, so that any cancellation or // interruption of the sync // keeps the local state in sync with what's on the // server final int updates = provider.update(localUri, ss.remoteCVs, null, null); final String locUriString = localUri.toString(); if (updates == 1) { ss.state = SyncState.NOW_UP_TO_DATE; ss.local = localUri; // ensure that it's findable by local URI too syncStatuses.put(locUriString, ss); syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson, true); count++; syncResult.stats.numUpdates++; } else { Log.e(TAG, "error updating " + locUriString); syncResult.stats.numSkippedEntries++; } syncResult.stats.numEntries++; } catch (final JSONException e) { if (DEBUG) { Log.e(TAG, "result was " + newJo.toString()); } throw e; } } finally { intent = new Intent(SYNC_STATUS_CHANGED); intent.putExtra(EXTRA_SYNC_STATUS, "castEnd"); intent.putExtra(EXTRA_SYNC_ID, id); mContext.sendStickyBroadcast(intent); } } } finally { uploadMe.close(); } return count; }
From source file:org.gege.caldavsyncadapter.syncadapter.SyncAdapter.java
/** * checks the android events for the dirty flag. * the flag is set by android when the event has been changed. * the dirty flag is removed when an android event has been updated from calendar event * @param provider/*from ww w. j a va 2s .co m*/ * @param account * @param calendarUri * @param facade * @param caldavCalendarUri * @param stats * @param notifyList * @return count of dirty events */ private int checkDirtyAndroidEvents(ContentProviderClient provider, Account account, Uri calendarUri, CaldavFacade facade, URI caldavCalendarUri, SyncStats stats, ArrayList<Uri> notifyList) { Cursor curEvent = null; Cursor curAttendee = null; Cursor curReminder = null; Long EventID; Long CalendarID; AndroidEvent androidEvent = null; int rowDirty = 0; int rowInsert = 0; int rowUpdate = 0; int rowDelete = 0; try { CalendarID = ContentUris.parseId(calendarUri); String selection = "(" + Events.DIRTY + " = ?) AND (" + Events.CALENDAR_ID + " = ?)"; String[] selectionArgs = new String[] { "1", CalendarID.toString() }; curEvent = provider.query(Events.CONTENT_URI, null, selection, selectionArgs, null); while (curEvent.moveToNext()) { EventID = curEvent.getLong(curEvent.getColumnIndex(Events._ID)); Uri returnedUri = ContentUris.withAppendedId(Events.CONTENT_URI, EventID); androidEvent = new AndroidEvent(account, provider, returnedUri, calendarUri); androidEvent.readContentValues(curEvent); selection = "(" + Attendees.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curAttendee = provider.query(Attendees.CONTENT_URI, null, selection, selectionArgs, null); selection = "(" + Reminders.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curReminder = provider.query(Reminders.CONTENT_URI, null, selection, selectionArgs, null); androidEvent.readAttendees(curAttendee); androidEvent.readReminder(curReminder); curAttendee.close(); curReminder.close(); String SyncID = androidEvent.ContentValues.getAsString(Events._SYNC_ID); boolean Deleted = false; int intDeleted = 0; intDeleted = curEvent.getInt(curEvent.getColumnIndex(Events.DELETED)); Deleted = (intDeleted == 1); if (SyncID == null) { // new Android event String newGUID = java.util.UUID.randomUUID().toString() + "-caldavsyncadapter"; String calendarPath = caldavCalendarUri.getPath(); if (!calendarPath.endsWith("/")) calendarPath += "/"; SyncID = calendarPath + newGUID + ".ics"; androidEvent.createIcs(newGUID); if (facade.createEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString())) { //HINT: bugfix for google calendar if (SyncID.contains("@")) SyncID = SyncID.replace("@", "%40"); ContentValues values = new ContentValues(); values.put(Events._SYNC_ID, SyncID); //google doesn't send the etag after creation //HINT: my SabreDAV send always the same etag after putting a new event //String LastETag = facade.getLastETag(); //if (!LastETag.equals("")) { // values.put(Event.ETAG, LastETag); //} else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); values.put(Event.ETAG, calendarEvent.getETag()); //} values.put(Event.UID, newGUID); values.put(Events.DIRTY, 0); values.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int rowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), values, null, null); if (rowCount == 1) { rowInsert += 1; notifyList.add(androidEvent.getUri()); } } } else if (Deleted) { // deleted Android event if (facade.deleteEvent(URI.create(SyncID), androidEvent.getETag())) { String mSelectionClause = "(" + Events._ID + "= ?)"; String[] mSelectionArgs = { String.valueOf(EventID) }; int countDeleted = provider.delete( asSyncAdapter(Events.CONTENT_URI, account.name, account.type), mSelectionClause, mSelectionArgs); if (countDeleted == 1) { rowDelete += 1; notifyList.add(androidEvent.getUri()); } } } else { //update the android event to the server String uid = androidEvent.getUID(); if ((uid == null) || (uid.equals(""))) { //COMPAT: this is needed because in the past, the UID was not stored in the android event CalendarEvent calendarEvent = new CalendarEvent(account, provider); URI syncURI = new URI(SyncID); calendarEvent.setUri(syncURI); calendarEvent.calendarURL = caldavCalendarUri.toURL(); if (calendarEvent.fetchBody()) { calendarEvent.readContentValues(); uid = calendarEvent.getUID(); } } if (uid != null) { androidEvent.createIcs(uid); if (facade.updateEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString(), androidEvent.getETag())) { selection = "(" + Events._ID + "= ?)"; selectionArgs = new String[] { EventID.toString() }; androidEvent.ContentValues.put(Events.DIRTY, 0); //google doesn't send the etag after update String LastETag = facade.getLastETag(); if (!LastETag.equals("")) { androidEvent.ContentValues.put(Event.ETAG, LastETag); } else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); androidEvent.ContentValues.put(Event.ETAG, calendarEvent.getETag()); } androidEvent.ContentValues.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int RowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), androidEvent.ContentValues, null, null); if (RowCount == 1) { rowUpdate += 1; notifyList.add(androidEvent.getUri()); } } else { rowDirty += 1; } } else { rowDirty += 1; } } } curEvent.close(); /*if ((rowInsert > 0) || (rowUpdate > 0) || (rowDelete > 0) || (rowDirty > 0)) { Log.i(TAG,"Android Rows inserted: " + String.valueOf(rowInsert)); Log.i(TAG,"Android Rows updated: " + String.valueOf(rowUpdate)); Log.i(TAG,"Android Rows deleted: " + String.valueOf(rowDelete)); Log.i(TAG,"Android Rows dirty: " + String.valueOf(rowDirty)); }*/ stats.numInserts += rowInsert; stats.numUpdates += rowUpdate; stats.numDeletes += rowDelete; stats.numSkippedEntries += rowDirty; stats.numEntries += rowInsert + rowUpdate + rowDelete; } catch (RemoteException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (IOException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (CaldavProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ParserException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } return rowDirty; }
From source file:org.totschnig.myexpenses.sync.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {// ww w .j a v a 2 s .c om categoryToId = new HashMap<>(); payeeToId = new HashMap<>(); methodToId = new HashMap<>(); accountUuidToId = new HashMap<>(); String uuidFromExtras = extras.getString(KEY_UUID); Timber.i("onPerformSync " + extras.toString()); AccountManager accountManager = AccountManager.get(getContext()); Exceptional<SyncBackendProvider> backendProviderExceptional = SyncBackendProviderFactory.get(getContext(), account); SyncBackendProvider backend; try { backend = backendProviderExceptional.getOrThrow(); } catch (Throwable throwable) { syncResult.databaseError = true; AcraHelper.report(throwable instanceof Exception ? ((Exception) throwable) : new Exception(throwable)); GenericAccountService.deactivateSync(account); accountManager.setUserData(account, GenericAccountService.KEY_BROKEN, "1"); String content = String.format(Locale.ROOT, "The backend could not be instantiated.Reason: %s. Please try to delete and recreate it.", throwable.getMessage()); Intent manageIntent = new Intent(getContext(), ManageSyncBackends.class); NotificationBuilderWrapper builder = NotificationBuilderWrapper .defaultBigTextStyleBuilder(getContext(), "Synchronization backend deactivated", content) .setContentIntent(PendingIntent.getActivity(getContext(), 0, manageIntent, PendingIntent.FLAG_CANCEL_CURRENT)); Notification notification = builder.build(); notification.flags = Notification.FLAG_AUTO_CANCEL; ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); return; } if (!backend.setUp()) { syncResult.stats.numIoExceptions++; syncResult.delayUntil = 300; return; } String autoBackupFileUri = extras.getString(KEY_UPLOAD_AUTO_BACKUP); if (autoBackupFileUri != null) { try { backend.storeBackup(Uri.parse(autoBackupFileUri)); } catch (IOException e) { String content = getContext().getString(R.string.auto_backup_cloud_failure, autoBackupFileUri, account.name) + " " + e.getMessage(); Notification notification = NotificationBuilderWrapper.defaultBigTextStyleBuilder(getContext(), getContext().getString(R.string.pref_auto_backup_title), content).build(); notification.flags = Notification.FLAG_AUTO_CANCEL; ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); } return; } Cursor c; String[] selectionArgs; String selection = KEY_SYNC_ACCOUNT_NAME + " = ?"; if (uuidFromExtras != null) { selection += " AND " + KEY_UUID + " = ?"; selectionArgs = new String[] { account.name, uuidFromExtras }; } else { selectionArgs = new String[] { account.name }; } String[] projection = { KEY_ROWID }; try { c = provider.query(TransactionProvider.ACCOUNTS_URI, projection, selection + " AND " + KEY_SYNC_SEQUENCE_LOCAL + " = 0", selectionArgs, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } if (c == null) { syncResult.databaseError = true; AcraHelper.report("Cursor is null"); return; } if (c.moveToFirst()) { do { long accountId = c.getLong(0); try { provider.update(buildInitializationUri(accountId), new ContentValues(0), null, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } } while (c.moveToNext()); } try { c = provider.query(TransactionProvider.ACCOUNTS_URI, projection, selection, selectionArgs, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } if (c != null) { if (c.moveToFirst()) { do { long accountId = c.getLong(0); String lastLocalSyncKey = KEY_LAST_SYNCED_LOCAL(accountId); String lastRemoteSyncKey = KEY_LAST_SYNCED_REMOTE(accountId); long lastSyncedLocal = Long .parseLong(getUserDataWithDefault(accountManager, account, lastLocalSyncKey, "0")); long lastSyncedRemote = Long .parseLong(getUserDataWithDefault(accountManager, account, lastRemoteSyncKey, "0")); dbAccount.set(org.totschnig.myexpenses.model.Account.getInstanceFromDb(accountId)); Timber.i("now syncing " + dbAccount.get().label); if (uuidFromExtras != null && extras.getBoolean(KEY_RESET_REMOTE_ACCOUNT)) { if (!backend.resetAccountData(uuidFromExtras)) { syncResult.stats.numIoExceptions++; Timber.e("error resetting account data"); } continue; } if (!backend.withAccount(dbAccount.get())) { syncResult.stats.numIoExceptions++; Timber.e("error withAccount"); continue; } if (backend.lock()) { try { ChangeSet changeSetSince = backend.getChangeSetSince(lastSyncedRemote, getContext()); if (changeSetSince.isFailed()) { syncResult.stats.numIoExceptions++; Timber.e("error getting changeset"); continue; } List<TransactionChange> remoteChanges; lastSyncedRemote = changeSetSince.sequenceNumber; remoteChanges = changeSetSince.changes; List<TransactionChange> localChanges = new ArrayList<>(); long sequenceToTest = lastSyncedLocal + 1; while (true) { List<TransactionChange> nextChanges = getLocalChanges(provider, accountId, sequenceToTest); if (nextChanges.size() > 0) { localChanges.addAll( Stream.of(nextChanges).filter(change -> !change.isEmpty()).toList()); lastSyncedLocal = sequenceToTest; sequenceToTest++; } else { break; } } if (localChanges.size() == 0 && remoteChanges.size() == 0) { continue; } if (localChanges.size() > 0) { localChanges = collectSplits(localChanges); } Pair<List<TransactionChange>, List<TransactionChange>> mergeResult = mergeChangeSets( localChanges, remoteChanges); localChanges = mergeResult.first; remoteChanges = mergeResult.second; if (remoteChanges.size() > 0) { writeRemoteChangesToDb(provider, Stream.of(remoteChanges) .filter(change -> !(change.isCreate() && uuidExists(change.uuid()))) .toList(), accountId); accountManager.setUserData(account, lastRemoteSyncKey, String.valueOf(lastSyncedRemote)); } if (localChanges.size() > 0) { lastSyncedRemote = backend.writeChangeSet(localChanges, getContext()); if (lastSyncedRemote != ChangeSet.FAILED) { if (!BuildConfig.DEBUG) { // on debug build for auditing purposes, we keep changes in the table provider.delete(TransactionProvider.CHANGES_URI, KEY_ACCOUNTID + " = ? AND " + KEY_SYNC_SEQUENCE_LOCAL + " <= ?", new String[] { String.valueOf(accountId), String.valueOf(lastSyncedLocal) }); } accountManager.setUserData(account, lastLocalSyncKey, String.valueOf(lastSyncedLocal)); accountManager.setUserData(account, lastRemoteSyncKey, String.valueOf(lastSyncedRemote)); } } } catch (IOException e) { Timber.e(e, "Error while syncing "); syncResult.stats.numIoExceptions++; } catch (RemoteException | OperationApplicationException | SQLiteException e) { Timber.e(e, "Error while syncing "); syncResult.databaseError = true; AcraHelper.report(e); } finally { if (!backend.unlock()) { Timber.e("Unlocking backend failed"); syncResult.stats.numIoExceptions++; } } } else { //TODO syncResult.delayUntil = ??? syncResult.stats.numIoExceptions++; } } while (c.moveToNext()); } c.close(); } backend.tearDown(); }