use of android.content.ContentProviderOperation in project SeriesGuide by UweTrottmann.
the class TraktTools method downloadEpisodeRatings.
/**
* Downloads trakt episode ratings and applies the latest ones to the database.
*
* <p> To apply all ratings, set {@link TraktSettings#KEY_LAST_EPISODES_RATED_AT} to 0.
*/
public UpdateResult downloadEpisodeRatings(@Nullable DateTime ratedAt) {
if (ratedAt == null) {
Timber.e("downloadEpisodeRatings: null rated_at");
return UpdateResult.INCOMPLETE;
}
long lastRatedAt = TraktSettings.getLastEpisodesRatedAt(context);
if (!ratedAt.isAfter(lastRatedAt)) {
// not initial sync, no ratings have changed
Timber.d("downloadEpisodeRatings: no changes since %tF %tT", lastRatedAt, lastRatedAt);
return UpdateResult.SUCCESS;
}
if (!TraktCredentials.get(context).hasCredentials()) {
return UpdateResult.INCOMPLETE;
}
// download rated episodes
List<RatedEpisode> ratedEpisodes;
try {
Response<List<RatedEpisode>> response = traktSync.get().ratingsEpisodes(RatingsFilter.ALL, Extended.DEFAULT_MIN).execute();
if (response.isSuccessful()) {
ratedEpisodes = response.body();
} else {
if (SgTrakt.isUnauthorized(context, response)) {
return UpdateResult.INCOMPLETE;
}
SgTrakt.trackFailedRequest(context, "get episode ratings", response);
return UpdateResult.INCOMPLETE;
}
} catch (IOException e) {
SgTrakt.trackFailedRequest(context, "get episode ratings", e);
return UpdateResult.INCOMPLETE;
}
if (ratedEpisodes == null) {
Timber.e("downloadEpisodeRatings: null response");
return UpdateResult.INCOMPLETE;
}
if (ratedEpisodes.isEmpty()) {
Timber.d("downloadEpisodeRatings: no ratings on trakt");
return UpdateResult.SUCCESS;
}
// trakt last activity rated_at timestamp is set after the rating timestamp
// so include ratings that are a little older
long ratedAtThreshold = lastRatedAt - 5 * DateUtils.MINUTE_IN_MILLIS;
ArrayList<ContentProviderOperation> batch = new ArrayList<>();
for (RatedEpisode episode : ratedEpisodes) {
if (episode.rating == null || episode.episode == null || episode.episode.ids == null || episode.episode.ids.tvdb == null) {
// skip, can't handle
continue;
}
if (episode.rated_at != null && episode.rated_at.isBefore(ratedAtThreshold)) {
// no need to apply older ratings again
break;
}
// if an episode does not exist, this update will do nothing
ContentProviderOperation op = ContentProviderOperation.newUpdate(SeriesGuideContract.Episodes.buildEpisodeUri(episode.episode.ids.tvdb)).withValue(SeriesGuideContract.Episodes.RATING_USER, episode.rating.value).build();
batch.add(op);
}
// apply database updates
try {
DBUtils.applyInSmallBatches(context, batch);
} catch (OperationApplicationException e) {
Timber.e(e, "downloadEpisodeRatings: database update failed");
return UpdateResult.INCOMPLETE;
}
// save last rated instant
PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(TraktSettings.KEY_LAST_EPISODES_RATED_AT, ratedAt.getMillis()).commit();
Timber.d("downloadEpisodeRatings: success, last rated_at %tF %tT", ratedAt.getMillis(), ratedAt.getMillis());
return UpdateResult.SUCCESS;
}
use of android.content.ContentProviderOperation in project SeriesGuide by UweTrottmann.
the class TraktTools method processTraktShows.
private int processTraktShows(@NonNull List<BaseShow> remoteShows, @NonNull HashSet<Integer> localShows, boolean isInitialSync, Flag flag) {
HashMap<Integer, BaseShow> traktShows = buildTraktShowsMap(remoteShows);
int uploadedShowsCount = 0;
final ArrayList<ContentProviderOperation> batch = new ArrayList<>();
for (Integer localShow : localShows) {
if (traktShows.containsKey(localShow)) {
// show watched/collected on trakt
BaseShow traktShow = traktShows.get(localShow);
int result = processTraktSeasons(isInitialSync, localShow, traktShow, flag);
if (result < SUCCESS) {
// processing seasons failed, give up.
return result;
}
if (flag == Flag.WATCHED) {
updateLastWatchedTime(localShow, traktShow, batch);
}
} else {
// show not watched/collected on trakt
// check if this is because the show can not be tracked with trakt (yet)
// some shows only exist on TheTVDB, keep state local and maybe upload in the future
Integer showTraktId = ShowTools.getShowTraktId(context, localShow);
if (showTraktId != null) {
if (isInitialSync) {
// upload all watched/collected episodes of the show
// do in between processing to stretch uploads over longer time periods
uploadEpisodes(localShow, showTraktId, flag);
uploadedShowsCount++;
} else {
// set all watched/collected episodes of show not watched/collected
batch.add(ContentProviderOperation.newUpdate(SeriesGuideContract.Episodes.buildEpisodesOfShowUri(localShow)).withSelection(flag.clearFlagSelection, null).withValue(flag.databaseColumn, flag.notFlaggedValue).build());
}
}
}
}
try {
DBUtils.applyInSmallBatches(context, batch);
} catch (OperationApplicationException e) {
Timber.e(e, "processTraktShows: failed to remove flag for %s.", flag.name);
}
if (uploadedShowsCount > 0) {
Timber.d("processTraktShows: uploaded %s flags for %s complete shows.", flag.name, localShows.size());
}
return SUCCESS;
}
use of android.content.ContentProviderOperation in project SeriesGuide by UweTrottmann.
the class TraktTools method downloadMovieRatings.
/**
* Downloads trakt movie ratings and applies the latest ones to the database.
*
* <p> To apply all ratings, set {@link TraktSettings#KEY_LAST_MOVIES_RATED_AT} to 0.
*/
public UpdateResult downloadMovieRatings(DateTime ratedAt) {
if (ratedAt == null) {
Timber.e("downloadMovieRatings: null rated_at");
return UpdateResult.INCOMPLETE;
}
long lastRatedAt = TraktSettings.getLastMoviesRatedAt(context);
if (!ratedAt.isAfter(lastRatedAt)) {
// not initial sync, no ratings have changed
Timber.d("downloadMovieRatings: no changes since %tF %tT", lastRatedAt, lastRatedAt);
return UpdateResult.SUCCESS;
}
if (!TraktCredentials.get(context).hasCredentials()) {
return UpdateResult.INCOMPLETE;
}
// download rated shows
List<RatedMovie> ratedMovies;
try {
Response<List<RatedMovie>> response = traktSync.get().ratingsMovies(RatingsFilter.ALL, Extended.DEFAULT_MIN).execute();
if (response.isSuccessful()) {
ratedMovies = response.body();
} else {
if (SgTrakt.isUnauthorized(context, response)) {
return UpdateResult.INCOMPLETE;
}
SgTrakt.trackFailedRequest(context, "get movie ratings", response);
return UpdateResult.INCOMPLETE;
}
} catch (IOException e) {
SgTrakt.trackFailedRequest(context, "get movie ratings", e);
return UpdateResult.INCOMPLETE;
}
if (ratedMovies == null) {
Timber.e("downloadMovieRatings: null response");
return UpdateResult.INCOMPLETE;
}
if (ratedMovies.isEmpty()) {
Timber.d("downloadMovieRatings: no ratings on trakt");
return UpdateResult.SUCCESS;
}
// trakt last activity rated_at timestamp is set after the rating timestamp
// so include ratings that are a little older
long ratedAtThreshold = lastRatedAt - 5 * DateUtils.MINUTE_IN_MILLIS;
// go through ratings, latest first (trakt sends in that order)
ArrayList<ContentProviderOperation> batch = new ArrayList<>();
for (RatedMovie movie : ratedMovies) {
if (movie.rating == null || movie.movie == null || movie.movie.ids == null || movie.movie.ids.tmdb == null) {
// skip, can't handle
continue;
}
if (movie.rated_at != null && movie.rated_at.isBefore(ratedAtThreshold)) {
// no need to apply older ratings again
break;
}
// if a movie does not exist, this update will do nothing
ContentProviderOperation op = ContentProviderOperation.newUpdate(SeriesGuideContract.Movies.buildMovieUri(movie.movie.ids.tmdb)).withValue(SeriesGuideContract.Movies.RATING_USER, movie.rating.value).build();
batch.add(op);
}
// apply database updates
try {
DBUtils.applyInSmallBatches(context, batch);
} catch (OperationApplicationException e) {
Timber.e(e, "downloadMovieRatings: database update failed");
return UpdateResult.INCOMPLETE;
}
// save last rated instant
PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(TraktSettings.KEY_LAST_MOVIES_RATED_AT, ratedAt.getMillis()).commit();
Timber.d("downloadMovieRatings: success, last rated_at %tF %tT", ratedAt.getMillis(), ratedAt.getMillis());
return UpdateResult.SUCCESS;
}
use of android.content.ContentProviderOperation in project Meltdown by phubbard.
the class MeltdownApp method doCPtest.
public void doCPtest() {
ContentResolver cr = getContentResolver();
List<Integer> items = fetchUnreadItemsIDs();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
// Get data in max-fever-size chunks
final int PER_FETCH = 50;
final int num_fetches = (int) Math.ceil(items.size() / PER_FETCH) + 1;
for (int idx = 0; idx < num_fetches; idx++) {
int left_index = idx * PER_FETCH;
int right_index = Math.min((idx + 1) * PER_FETCH, items.size());
Log.d(TAG, "On run " + idx + " pulling from " + left_index + " to " + (right_index - 1) + " of " + items.size());
List<Integer> ids = items.subList(left_index, right_index);
String payload = xcvr.fetchListOfItems(ids);
for (int j = 0; j < ids.size(); j++) {
JSONArray jitems;
RssItem this_item;
try {
JSONObject jdata = new JSONObject(payload);
jitems = jdata.getJSONArray("items");
this_item = new RssItem(jitems.getJSONObject(j));
ops.add(ContentProviderOperation.newInsert(ItemProvider.URI).withYieldAllowed(true).withValues(this_item.getCV()).build());
} catch (JSONException je) {
Log.e(TAG, "JSON error in CP import logic: ", je);
} finally {
}
}
}
try {
cr.applyBatch(ItemProvider.AUTHORITY, ops);
} catch (RemoteException e) {
Log.e(TAG, "Remote exception in bulk save", e);
e.printStackTrace();
} catch (OperationApplicationException e) {
Log.e(TAG, "OAE exception in bulk save", e);
e.printStackTrace();
}
cr.notifyChange(ItemProvider.URI, null, false);
}
use of android.content.ContentProviderOperation in project jpHolo by teusink.
the class ContactAccessorSdk5 method modifyContact.
/**
* Creates a new contact and stores it in the database
*
* @param id the raw contact id which is required for linking items to the contact
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
// Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
// But not needed to update existing values.
int rawId = (Integer.valueOf(getJsonString(contact, "rawId"))).intValue();
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());
// Modify name
JSONObject name;
try {
String displayName = getJsonString(contact, "displayName");
name = contact.getJSONObject("name");
if (displayName != null || name != null) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });
if (displayName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
}
String familyName = getJsonString(name, "familyName");
if (familyName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
}
String middleName = getJsonString(name, "middleName");
if (middleName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
}
String givenName = getJsonString(name, "givenName");
if (givenName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
}
String honorificPrefix = getJsonString(name, "honorificPrefix");
if (honorificPrefix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
}
String honorificSuffix = getJsonString(name, "honorificSuffix");
if (honorificSuffix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
}
ops.add(builder.build());
}
} catch (JSONException e1) {
Log.d(LOG_TAG, "Could not get name");
}
// Modify phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
// Delete all the phones
if (phones.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a phone
{
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
String phoneId = getJsonString(phone, "id");
// This is a new phone so do a DB insert
if (phoneId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing phone so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value")).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Modify emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
// Delete all the emails
if (emails.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a email
{
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
String emailId = getJsonString(email, "id");
// This is a new email so do a DB insert
if (emailId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing email so do a DB update
{
String emailValue = getJsonString(email, "value");
if (!emailValue.isEmpty()) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value")).withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type"))).build());
} else {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }).build());
}
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
// Delete all the addresses
if (addresses.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a address
{
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
String addressId = getJsonString(address, "id");
// This is a new address so do a DB insert
if (addressId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing address so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { addressId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type"))).withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country")).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Modify organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
// Delete all the organizations
if (organizations.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a organization
{
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
String orgId = getJsonString(org, "id");
// This is a new organization so do a DB insert
if (orgId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")));
contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing organization so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Organization._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { orgId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type"))).withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department")).withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name")).withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title")).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Modify IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
// Delete all the ims
if (ims.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a im
{
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
String imId = getJsonString(im, "id");
// This is a new IM so do a DB insert
if (imId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE, getImType(getJsonString(im, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing IM so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Im._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value")).withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify note
String note = getJsonString(contact, "note");
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());
// Modify nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
}
// Modify urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
// Delete all the websites
if (websites.length() == 0) {
Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a website
{
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
String websiteId = getJsonString(website, "id");
// This is a new website so do a DB insert
if (websiteId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing website so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Website._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { websiteId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value")).withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Modify birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) }).withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY).withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
}
// Modify photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
// Delete all the photos
if (photos.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a photo
{
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
String photoId = getJsonString(photo, "id");
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
// This is a new photo so do a DB insert
if (photoId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing photo so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Photo._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE }).withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1).withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
boolean retVal = true;
//Modify contact
try {
mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
}
// if the save was a success return the contact ID
if (retVal) {
return id;
} else {
return null;
}
}
Aggregations