Search in sources :

Example 21 with ContentProviderResult

use of android.content.ContentProviderResult in project jpHolo by teusink.

the class ContactAccessorSdk5 method createNewContact.

/**
 * Creates a new contact and stores it in the database
 *
 * @param contact the contact to be saved
 * @param account the account to be saved under
 */
private String createNewContact(JSONObject contact, String accountType, String accountName) {
    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    // Add contact type
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());
    // Add name
    try {
        JSONObject name = contact.optJSONObject("name");
        String displayName = contact.getString("displayName");
        if (displayName != null || name != null) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName).withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, getJsonString(name, "familyName")).withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, getJsonString(name, "middleName")).withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, getJsonString(name, "givenName")).withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, getJsonString(name, "honorificPrefix")).withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, getJsonString(name, "honorificSuffix")).build());
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get name object");
    }
    // Add phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            for (int i = 0; i < phones.length(); i++) {
                JSONObject phone = (JSONObject) phones.get(i);
                insertPhone(ops, phone);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }
    // Add emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            for (int i = 0; i < emails.length(); i++) {
                JSONObject email = (JSONObject) emails.get(i);
                insertEmail(ops, email);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }
    // Add addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            for (int i = 0; i < addresses.length(); i++) {
                JSONObject address = (JSONObject) addresses.get(i);
                insertAddress(ops, address);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }
    // Add organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            for (int i = 0; i < organizations.length(); i++) {
                JSONObject org = (JSONObject) organizations.get(i);
                insertOrganization(ops, org);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }
    // Add IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            for (int i = 0; i < ims.length(); i++) {
                JSONObject im = (JSONObject) ims.get(i);
                insertIm(ops, im);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }
    // Add note
    String note = getJsonString(contact, "note");
    if (note != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());
    }
    // Add nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }
    // Add urls
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("urls");
        if (websites != null) {
            for (int i = 0; i < websites.length(); i++) {
                JSONObject website = (JSONObject) websites.get(i);
                insertWebsite(ops, website);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }
    // Add birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY).withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }
    // Add photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            for (int i = 0; i < photos.length(); i++) {
                JSONObject photo = (JSONObject) photos.get(i);
                insertPhoto(ops, photo);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }
    String newId = null;
    // Add contact
    try {
        ContentProviderResult[] cpResults = mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        if (cpResults.length >= 0) {
            newId = cpResults[0].uri.getLastPathSegment();
        }
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return newId;
}
Also used : ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 22 with ContentProviderResult

use of android.content.ContentProviderResult in project android by owncloud.

the class FileDataStorageManager method saveFolder.

/**
     * Inserts or updates the list of files contained in a given folder.
     * <p/>
     * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
     * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
     *
     * @param folder
     * @param updatedFiles
     * @param filesToRemove
     */
public void saveFolder(OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove) {
    Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size() + " children and " + filesToRemove.size() + " files to remove");
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(updatedFiles.size());
    // prepare operations to insert or update files to save in the given folder
    for (OCFile file : updatedFiles) {
        ContentValues cv = new ContentValues();
        cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
        cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
        cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
        cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
        cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
        cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
        cv.put(ProviderTableMeta.FILE_PARENT, folder.getFileId());
        cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
        if (!file.isFolder()) {
            cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
        }
        cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
        cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
        cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
        cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
        cv.put(ProviderTableMeta.FILE_TREE_ETAG, file.getTreeEtag());
        cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0);
        cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0);
        cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
        cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
        cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
        cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail());
        cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading());
        cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict());
        boolean existsByPath = fileExists(file.getRemotePath());
        if (existsByPath || fileExists(file.getFileId())) {
            // updating an existing file
            operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection(ProviderTableMeta._ID + "=?", new String[] { String.valueOf(file.getFileId()) }).build());
        } else {
            // adding a new file
            setInitialAvailableOfflineStatus(file, cv);
            operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
        }
    }
    // prepare operations to remove files in the given folder
    String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
    String[] whereArgs = null;
    for (OCFile file : filesToRemove) {
        if (file.getParentId() == folder.getFileId()) {
            whereArgs = new String[] { mAccount.name, file.getRemotePath() };
            if (file.isFolder()) {
                operations.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, file.getFileId())).withSelection(where, whereArgs).build());
                File localFolder = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
                if (localFolder.exists()) {
                    removeLocalFolder(localFolder);
                }
            } else {
                operations.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId())).withSelection(where, whereArgs).build());
                if (file.isDown()) {
                    String path = file.getStoragePath();
                    new File(path).delete();
                    // notify MediaScanner about removed file
                    triggerMediaScan(path);
                }
            }
        }
    }
    // update metadata of folder
    ContentValues cv = new ContentValues();
    cv.put(ProviderTableMeta.FILE_MODIFIED, folder.getModificationTimestamp());
    cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, folder.getModificationTimestampAtLastSyncForData());
    cv.put(ProviderTableMeta.FILE_CREATION, folder.getCreationTimestamp());
    cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, folder.getFileLength());
    cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.getMimetype());
    cv.put(ProviderTableMeta.FILE_NAME, folder.getFileName());
    cv.put(ProviderTableMeta.FILE_PARENT, folder.getParentId());
    cv.put(ProviderTableMeta.FILE_PATH, folder.getRemotePath());
    cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
    cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, folder.getLastSyncDateForProperties());
    cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, folder.getLastSyncDateForData());
    cv.put(ProviderTableMeta.FILE_ETAG, folder.getEtag());
    cv.put(ProviderTableMeta.FILE_TREE_ETAG, folder.getTreeEtag());
    cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, folder.isSharedViaLink() ? 1 : 0);
    cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, folder.isSharedWithSharee() ? 1 : 0);
    cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, folder.getPublicLink());
    cv.put(ProviderTableMeta.FILE_PERMISSIONS, folder.getPermissions());
    cv.put(ProviderTableMeta.FILE_REMOTE_ID, folder.getRemoteId());
    operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection(ProviderTableMeta._ID + "=?", new String[] { String.valueOf(folder.getFileId()) }).build());
    // apply operations in batch
    ContentProviderResult[] results = null;
    Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
    try {
        if (getContentResolver() != null) {
            results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
        } else {
            results = getContentProviderClient().applyBatch(operations);
        }
    } catch (OperationApplicationException e) {
        Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
    } catch (RemoteException e) {
        Log_OC.e(TAG, "Exception in batch of operations  " + e.getMessage());
    }
    // update new id in file objects for insertions
    if (results != null) {
        long newId;
        Iterator<OCFile> filesIt = updatedFiles.iterator();
        OCFile file = null;
        for (int i = 0; i < results.length; i++) {
            if (filesIt.hasNext()) {
                file = filesIt.next();
            } else {
                file = null;
            }
            if (results[i].uri != null) {
                newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
                //updatedFiles.get(i).setFileId(newId);
                if (file != null) {
                    file.setFileId(newId);
                }
            }
        }
    }
}
Also used : ContentValues(android.content.ContentValues) ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) RemoteException(android.os.RemoteException) File(java.io.File) OperationApplicationException(android.content.OperationApplicationException)

Example 23 with ContentProviderResult

use of android.content.ContentProviderResult in project android_frameworks_base by ResurrectionRemix.

the class TvInputManagerService method registerBroadcastReceivers.

private void registerBroadcastReceivers() {
    PackageMonitor monitor = new PackageMonitor() {

        private void buildTvInputList(String[] packages) {
            synchronized (mLock) {
                if (mCurrentUserId == getChangingUserId()) {
                    buildTvInputListLocked(mCurrentUserId, packages);
                    buildTvContentRatingSystemListLocked(mCurrentUserId);
                }
            }
        }

        @Override
        public void onPackageUpdateFinished(String packageName, int uid) {
            if (DEBUG)
                Slog.d(TAG, "onPackageUpdateFinished(packageName=" + packageName + ")");
            // This callback is invoked when the TV input is reinstalled.
            // In this case, isReplacing() always returns true.
            buildTvInputList(new String[] { packageName });
        }

        @Override
        public void onPackagesAvailable(String[] packages) {
            if (DEBUG) {
                Slog.d(TAG, "onPackagesAvailable(packages=" + Arrays.toString(packages) + ")");
            }
            // available.
            if (isReplacing()) {
                buildTvInputList(packages);
            }
        }

        @Override
        public void onPackagesUnavailable(String[] packages) {
            // unavailable.
            if (DEBUG) {
                Slog.d(TAG, "onPackagesUnavailable(packages=" + Arrays.toString(packages) + ")");
            }
            if (isReplacing()) {
                buildTvInputList(packages);
            }
        }

        @Override
        public void onSomePackagesChanged() {
            // the TV inputs.
            if (DEBUG)
                Slog.d(TAG, "onSomePackagesChanged()");
            if (isReplacing()) {
                if (DEBUG)
                    Slog.d(TAG, "Skipped building TV input list due to replacing");
                // methods instead.
                return;
            }
            buildTvInputList(null);
        }

        @Override
        public boolean onPackageChanged(String packageName, int uid, String[] components) {
            // the update can be handled in {@link #onSomePackagesChanged}.
            return true;
        }

        @Override
        public void onPackageRemoved(String packageName, int uid) {
            synchronized (mLock) {
                UserState userState = getOrCreateUserStateLocked(getChangingUserId());
                if (!userState.packageSet.contains(packageName)) {
                    // Not a TV input package.
                    return;
                }
            }
            ArrayList<ContentProviderOperation> operations = new ArrayList<>();
            String selection = TvContract.BaseTvColumns.COLUMN_PACKAGE_NAME + "=?";
            String[] selectionArgs = { packageName };
            operations.add(ContentProviderOperation.newDelete(TvContract.Channels.CONTENT_URI).withSelection(selection, selectionArgs).build());
            operations.add(ContentProviderOperation.newDelete(TvContract.Programs.CONTENT_URI).withSelection(selection, selectionArgs).build());
            operations.add(ContentProviderOperation.newDelete(TvContract.WatchedPrograms.CONTENT_URI).withSelection(selection, selectionArgs).build());
            ContentProviderResult[] results = null;
            try {
                ContentResolver cr = getContentResolverForUser(getChangingUserId());
                results = cr.applyBatch(TvContract.AUTHORITY, operations);
            } catch (RemoteException | OperationApplicationException e) {
                Slog.e(TAG, "error in applyBatch", e);
            }
            if (DEBUG) {
                Slog.d(TAG, "onPackageRemoved(packageName=" + packageName + ", uid=" + uid + ")");
                Slog.d(TAG, "results=" + results);
            }
        }
    };
    monitor.register(mContext, null, UserHandle.ALL, true);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
    intentFilter.addAction(Intent.ACTION_USER_REMOVED);
    mContext.registerReceiverAsUser(new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_USER_SWITCHED.equals(action)) {
                switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
                removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
            }
        }
    }, UserHandle.ALL, intentFilter, null, null);
}
Also used : Context(android.content.Context) ContentProviderResult(android.content.ContentProviderResult) IntentFilter(android.content.IntentFilter) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) Intent(android.content.Intent) BroadcastReceiver(android.content.BroadcastReceiver) PackageMonitor(com.android.internal.content.PackageMonitor) ContentResolver(android.content.ContentResolver) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 24 with ContentProviderResult

use of android.content.ContentProviderResult in project android by nextcloud.

the class FileDataStorageManager method saveShares.

public void saveShares(Collection<OCShare> shares) {
    cleanShares();
    if (shares != null) {
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(shares.size());
        // prepare operations to insert or update files to save in the given folder
        for (OCShare share : shares) {
            ContentValues cv = new ContentValues();
            cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
            cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
            cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
            cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
            cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
            cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
            cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
            cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
            cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
            cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, share.getSharedWithDisplayName());
            cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
            cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
            cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getRemoteId());
            cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
            if (shareExistsForRemoteId(share.getRemoteId())) {
                // updating an existing file
                operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).withValues(cv).withSelection(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?", new String[] { String.valueOf(share.getRemoteId()) }).build());
            } else {
                // adding a new file
                operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).withValues(cv).build());
            }
        }
        // apply operations in batch
        if (operations.size() > 0) {
            @SuppressWarnings("unused") ContentProviderResult[] results = null;
            Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size()));
            try {
                if (getContentResolver() != null) {
                    results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
                } else {
                    results = getContentProviderClient().applyBatch(operations);
                }
            } catch (OperationApplicationException | RemoteException e) {
                Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage(), e);
            }
        }
    }
}
Also used : ContentValues(android.content.ContentValues) ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) OCShare(com.owncloud.android.lib.resources.shares.OCShare) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 25 with ContentProviderResult

use of android.content.ContentProviderResult in project android by nextcloud.

the class FileDataStorageManager method updateSharedFiles.

public void updateSharedFiles(Collection<OCFile> sharedFiles) {
    resetShareFlagsInAllFiles();
    if (sharedFiles != null) {
        ArrayList<ContentProviderOperation> operations = new ArrayList<>(sharedFiles.size());
        // prepare operations to insert or update files to save in the given folder
        for (OCFile file : sharedFiles) {
            ContentValues cv = new ContentValues();
            cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
            cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
            cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
            cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
            cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
            cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
            cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
            cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
            if (!file.isFolder()) {
                cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
            }
            cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
            cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
            cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
            cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.isAvailableOffline() ? 1 : 0);
            cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
            cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0);
            cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0);
            cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
            cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
            cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
            cv.put(ProviderTableMeta.FILE_FAVORITE, file.getIsFavorite());
            cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail() ? 1 : 0);
            cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading() ? 1 : 0);
            cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict());
            boolean existsByPath = fileExists(file.getRemotePath());
            if (existsByPath || fileExists(file.getFileId())) {
                // updating an existing file
                operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection(ProviderTableMeta._ID + "=?", new String[] { String.valueOf(file.getFileId()) }).build());
            } else {
                // adding a new file
                operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
            }
        }
        // apply operations in batch
        if (operations.size() > 0) {
            @SuppressWarnings("unused") ContentProviderResult[] results = null;
            Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size()));
            try {
                if (getContentResolver() != null) {
                    results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
                } else {
                    results = getContentProviderClient().applyBatch(operations);
                }
            } catch (OperationApplicationException | RemoteException e) {
                Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage(), e);
            }
        }
    }
}
Also used : ContentValues(android.content.ContentValues) ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Aggregations

ContentProviderResult (android.content.ContentProviderResult)39 ContentProviderOperation (android.content.ContentProviderOperation)30 OperationApplicationException (android.content.OperationApplicationException)22 ArrayList (java.util.ArrayList)20 RemoteException (android.os.RemoteException)17 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)12 ContentValues (android.content.ContentValues)9 Uri (android.net.Uri)9 ContentResolver (android.content.ContentResolver)6 Intent (android.content.Intent)6 NonNull (android.support.annotation.NonNull)6 BroadcastReceiver (android.content.BroadcastReceiver)4 Context (android.content.Context)4 IntentFilter (android.content.IntentFilter)4 PackageMonitor (com.android.internal.content.PackageMonitor)4 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)3 Test (org.junit.Test)3 ContentProvider (android.content.ContentProvider)2 OperationInfo (com.android.calendar.AsyncQueryServiceHelper.OperationInfo)2 OrgProperties (com.orgzly.org.OrgProperties)2