Search in sources :

Example 61 with OperationApplicationException

use of android.content.OperationApplicationException in project Timber by naman14.

the class PlaylistSongLoader method cleanupPlaylist.

private static void cleanupPlaylist(final Context context, final long playlistId, final Cursor cursor) {
    final int idCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newDelete(uri).build());
    final int YIELD_FREQUENCY = 100;
    if (cursor.moveToFirst() && cursor.getCount() > 0) {
        do {
            final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(uri).withValue(Playlists.Members.PLAY_ORDER, cursor.getPosition()).withValue(Playlists.Members.AUDIO_ID, cursor.getLong(idCol));
            if ((cursor.getPosition() + 1) % YIELD_FREQUENCY == 0) {
                builder.withYieldAllowed(true);
            }
            ops.add(builder.build());
        } while (cursor.moveToNext());
    }
    try {
        context.getContentResolver().applyBatch(MediaStore.AUTHORITY, ops);
    } catch (RemoteException e) {
    } catch (OperationApplicationException e) {
    }
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) RemoteException(android.os.RemoteException) Uri(android.net.Uri) OperationApplicationException(android.content.OperationApplicationException)

Example 62 with OperationApplicationException

use of android.content.OperationApplicationException in project android-ui-design-pattern by MathieuCalba.

the class YANAService method initData.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void initData() {
    Intent i = new Intent(InitDataReceiver.ACTION_INIT_DATA_CHANGE_STATE);
    i.putExtra(InitDataReceiver.EXTRA_STATE, true);
    mLocalBroadcastManager.sendBroadcast(i);
    final SharedPreferences pref = getSharedPreferences(PREF_DATA_NAME, MODE_PRIVATE);
    final boolean isDataInit = pref.getBoolean(PREF_DATA_IS_INIT_KEY, false);
    if (!isDataInit) {
        final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
        final Set<FeedsData.Article> articles = FeedsData.getArticles(this);
        for (final Iterator<FeedsData.Article> iterator = articles.iterator(); iterator.hasNext(); ) {
            final FeedsData.Article article = iterator.next();
            batch.add(createArticleInsertOpe(article));
        }
        final ContentResolver cr = getContentResolver();
        try {
            cr.applyBatch(YANAContract.CONTENT_AUTHORITY, batch);
            final SharedPreferences.Editor edit = pref.edit();
            edit.putBoolean(PREF_DATA_IS_INIT_KEY, true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                edit.apply();
            } else {
                edit.commit();
            }
        } catch (final RemoteException e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Impossible to add batch", e);
            }
        } catch (final OperationApplicationException e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Impossible to add batch", e);
            }
        }
    }
    i = new Intent(InitDataReceiver.ACTION_INIT_DATA_CHANGE_STATE);
    i.putExtra(InitDataReceiver.EXTRA_STATE, false);
    mLocalBroadcastManager.sendBroadcast(i);
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) FeedsData(com.mathieucalba.yana.model.FeedsData) SharedPreferences(android.content.SharedPreferences) ArrayList(java.util.ArrayList) Intent(android.content.Intent) ContentResolver(android.content.ContentResolver) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException) TargetApi(android.annotation.TargetApi)

Example 63 with OperationApplicationException

use of android.content.OperationApplicationException in project SeriesGuide by UweTrottmann.

the class HexagonListsSync method doListsDatabaseUpdate.

private boolean doListsDatabaseUpdate(List<SgList> lists, HashSet<String> localListIds, boolean hasMergedLists) {
    ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    for (SgList list : lists) {
        // add or update the list
        String listId = list.getListId();
        ContentProviderOperation.Builder builder = null;
        if (localListIds.contains(listId)) {
            // update
            if (hasMergedLists) {
                // only overwrite name and order if data was already merged
                // use case: user disconnected for a while, changed lists, then reconnects
                builder = ContentProviderOperation.newUpdate(SeriesGuideContract.Lists.buildListUri(listId));
            }
        } else {
            // insert
            builder = ContentProviderOperation.newInsert(SeriesGuideContract.Lists.CONTENT_URI).withValue(SeriesGuideContract.Lists.LIST_ID, listId);
        }
        if (builder != null) {
            builder.withValue(SeriesGuideContract.Lists.NAME, list.getName());
            if (list.getOrder() != null) {
                builder.withValue(SeriesGuideContract.Lists.ORDER, list.getOrder());
            }
            batch.add(builder.build());
        }
        // keep track of items not in the list on hexagon
        HashSet<String> listItemsToRemove = null;
        if (hasMergedLists) {
            listItemsToRemove = ListsTools.getListItemIds(context, listId);
            if (listItemsToRemove == null) {
                // list item query failed
                return false;
            }
        }
        // add or update items of the list
        List<SgListItem> listItems = list.getListItems();
        if (listItems != null) {
            for (SgListItem listItem : listItems) {
                String listItemId = listItem.getListItemId();
                String[] brokenUpId = SeriesGuideContract.ListItems.splitListItemId(listItemId);
                if (brokenUpId == null) {
                    // could not break up list item id
                    continue;
                }
                int itemTvdbId = -1;
                int itemType = -1;
                try {
                    itemTvdbId = Integer.parseInt(brokenUpId[0]);
                    itemType = Integer.parseInt(brokenUpId[1]);
                } catch (NumberFormatException ignored) {
                }
                if (itemTvdbId == -1 || !SeriesGuideContract.ListItems.isValidItemType(itemType)) {
                    // failed to extract item TVDB id or item type not known
                    continue;
                }
                // just insert the list item, if the id already exists it will be replaced
                builder = ContentProviderOperation.newInsert(SeriesGuideContract.ListItems.CONTENT_URI).withValue(SeriesGuideContract.ListItems.LIST_ITEM_ID, listItemId).withValue(SeriesGuideContract.ListItems.ITEM_REF_ID, itemTvdbId).withValue(SeriesGuideContract.ListItems.TYPE, itemType).withValue(SeriesGuideContract.Lists.LIST_ID, listId);
                batch.add(builder.build());
                if (hasMergedLists) {
                    // do not remove this list item
                    listItemsToRemove.remove(listItemId);
                }
            }
        }
        if (hasMergedLists) {
            // remove items no longer in the list
            for (String listItemId : listItemsToRemove) {
                builder = ContentProviderOperation.newDelete(SeriesGuideContract.ListItems.buildListItemUri(listItemId));
                batch.add(builder.build());
            }
        }
    }
    try {
        DBUtils.applyInSmallBatches(context, batch);
    } catch (OperationApplicationException e) {
        Timber.e(e, "doListsDatabaseUpdate: failed.");
        return false;
    }
    return true;
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) SgList(com.uwetrottmann.seriesguide.backend.lists.model.SgList) SgListItem(com.uwetrottmann.seriesguide.backend.lists.model.SgListItem) ArrayList(java.util.ArrayList) OperationApplicationException(android.content.OperationApplicationException)

Example 64 with OperationApplicationException

use of android.content.OperationApplicationException 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;
    }
}
Also used : ContentValues(android.content.ContentValues) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 65 with OperationApplicationException

use of android.content.OperationApplicationException in project SeriesGuide by UweTrottmann.

the class TraktMovieSync method syncLists.

/**
 * Updates the local movie database against trakt movie watchlist, collection and watched
 * movies. Adds or updates movies in the database. Movies not in any list or not watched must be
 * removed afterwards.
 *
 * <p> When syncing the first time, will upload any local movies missing from trakt collection
 * or watchlist or are not watched on Trakt instead of removing them locally.
 *
 * <p> Performs <b>synchronous network access</b>, make sure to run this on a background
 * thread.
 */
boolean syncLists(LastActivityMore activity) {
    if (activity.collected_at == null) {
        Timber.e("syncLists: null collected_at");
        return false;
    }
    if (activity.watchlisted_at == null) {
        Timber.e("syncLists: null watchlisted_at");
        return false;
    }
    if (activity.watched_at == null) {
        Timber.e("syncLists: null watched_at");
        return false;
    }
    final boolean merging = !TraktSettings.hasMergedMovies(context);
    if (!merging && !TraktSettings.isMovieListsChanged(context, activity.collected_at, activity.watchlisted_at, activity.watched_at)) {
        Timber.d("syncLists: no changes");
        return true;
    }
    if (!TraktCredentials.get(context).hasCredentials()) {
        return false;
    }
    // download trakt state
    Set<Integer> collection = downloadCollection();
    if (collection == null) {
        return false;
    }
    Set<Integer> watchlist = downloadWatchlist();
    if (watchlist == null) {
        return false;
    }
    Map<Integer, Integer> watchedWithPlays = downloadWatched();
    if (watchedWithPlays == null) {
        return false;
    }
    // Loop through local movies to build updates.
    List<SgMovieFlags> localMovies;
    try {
        localMovies = SgRoomDatabase.getInstance(context).movieHelper().getMovieFlags();
    } catch (Exception e) {
        Errors.logAndReport("syncLists: query local movies", e);
        return false;
    }
    // only when merging
    Set<Integer> toCollectOnTrakt = new HashSet<>();
    // only when merging
    Set<Integer> toWatchlistOnTrakt = new HashSet<>();
    // only when merging
    Set<Integer> toSetWatchedOnTrakt = new HashSet<>();
    ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    for (SgMovieFlags localMovie : localMovies) {
        // Is local movie in trakt collection, watchlist or watched?
        int tmdbId = localMovie.getTmdbId();
        boolean inCollectionOnTrakt = collection.remove(tmdbId);
        boolean inWatchlistOnTrakt = watchlist.remove(tmdbId);
        Integer plays = watchedWithPlays.remove(tmdbId);
        boolean isWatchedOnTrakt = plays != null;
        if (merging) {
            if (localMovie.getInCollection() && !inCollectionOnTrakt) {
                toCollectOnTrakt.add(tmdbId);
            }
            if (localMovie.getInWatchlist() && !inWatchlistOnTrakt) {
                toWatchlistOnTrakt.add(tmdbId);
            }
            if (localMovie.getWatched() && !isWatchedOnTrakt) {
                toSetWatchedOnTrakt.add(tmdbId);
            }
            // in later sync step.
            if (inCollectionOnTrakt || inWatchlistOnTrakt || isWatchedOnTrakt) {
                ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(Movies.buildMovieUri(tmdbId));
                boolean changed = false;
                if (!localMovie.getInCollection() && inCollectionOnTrakt) {
                    builder.withValue(Movies.IN_COLLECTION, true);
                    changed = true;
                }
                if (!localMovie.getInWatchlist() && inWatchlistOnTrakt) {
                    builder.withValue(Movies.IN_WATCHLIST, true);
                    changed = true;
                }
                if (!localMovie.getWatched() && isWatchedOnTrakt) {
                    builder.withValue(Movies.WATCHED, true);
                    builder.withValue(Movies.PLAYS, plays >= 1 ? plays : 1);
                    changed = true;
                }
                if (changed) {
                    batch.add(builder.build());
                }
            }
        } else {
            // Performance: only add op if any flag differs or if watched and plays have changed.
            if (localMovie.getInCollection() != inCollectionOnTrakt || localMovie.getInWatchlist() != inWatchlistOnTrakt || localMovie.getWatched() != isWatchedOnTrakt || (isWatchedOnTrakt && plays >= 1 && localMovie.getPlays() != plays)) {
                // Mirror Trakt collection, watchlist, watched flag and plays.
                // Note: unneeded (not watched or in any list) movies
                // are removed in a later sync step.
                ContentProviderOperation.Builder op = ContentProviderOperation.newUpdate(Movies.buildMovieUri(tmdbId)).withValue(Movies.IN_COLLECTION, inCollectionOnTrakt).withValue(Movies.IN_WATCHLIST, inWatchlistOnTrakt).withValue(Movies.WATCHED, isWatchedOnTrakt);
                int playsValue;
                if (isWatchedOnTrakt) {
                    playsValue = plays >= 1 ? plays : 1;
                } else {
                    playsValue = 0;
                }
                op.withValue(Movies.PLAYS, playsValue);
                batch.add(op.build());
            }
        }
    }
    // apply updates to existing movies
    try {
        DBUtils.applyInSmallBatches(context, batch);
        Timber.d("syncLists: updated %s", batch.size());
    } catch (OperationApplicationException e) {
        Timber.e(e, "syncLists: database updates failed");
        return false;
    }
    // release for gc
    batch.clear();
    // merge on first run
    if (merging) {
        // Upload movies not in Trakt collection, watchlist or watched history.
        if (uploadFlagsNotOnTrakt(toCollectOnTrakt, toWatchlistOnTrakt, toSetWatchedOnTrakt)) {
            // set merge successful
            PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(TraktSettings.KEY_HAS_MERGED_MOVIES, true).apply();
        } else {
            return false;
        }
    }
    // add movies from trakt missing locally
    // all local movies were removed from trakt collection, watchlist, and watched list
    // so they only contain movies missing locally
    boolean addingSuccessful = movieTools.addMovies(collection, watchlist, watchedWithPlays);
    if (addingSuccessful) {
        // store last activity timestamps
        TraktSettings.storeLastMoviesChangedAt(context, activity.collected_at, activity.watchlisted_at, activity.watched_at);
        // if movies were added, ensure ratings for them are downloaded next
        if (collection.size() > 0 || watchlist.size() > 0 || watchedWithPlays.size() > 0) {
            TraktSettings.resetMoviesLastRatedAt(context);
        }
    }
    return addingSuccessful;
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) OperationApplicationException(android.content.OperationApplicationException) SgMovieFlags(com.battlelancer.seriesguide.model.SgMovieFlags) OperationApplicationException(android.content.OperationApplicationException) HashSet(java.util.HashSet)

Aggregations

OperationApplicationException (android.content.OperationApplicationException)67 ContentProviderOperation (android.content.ContentProviderOperation)60 ArrayList (java.util.ArrayList)55 RemoteException (android.os.RemoteException)46 ContentProviderResult (android.content.ContentProviderResult)23 ContentValues (android.content.ContentValues)17 ContentResolver (android.content.ContentResolver)12 Cursor (android.database.Cursor)11 Uri (android.net.Uri)11 IOException (java.io.IOException)11 Intent (android.content.Intent)9 OCShare (com.owncloud.android.lib.resources.shares.OCShare)6 LinkedList (java.util.LinkedList)6 List (java.util.List)6 JSONArray (org.json.JSONArray)6 JSONException (org.json.JSONException)6 JSONObject (org.json.JSONObject)6 BroadcastReceiver (android.content.BroadcastReceiver)4 Context (android.content.Context)4 IntentFilter (android.content.IntentFilter)4