Search in sources :

Example 6 with ContentProviderResult

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

the class FileDataStorageManager method saveFolder.

/**
 * Inserts or updates the list of files contained in a given folder.
 *
 * CALLER IS 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<>(updatedFiles.size());
    // prepare operations to insert or update files to save in the given folder
    for (OCFile file : updatedFiles) {
        ContentValues cv = createContentValueForFile(file, folder);
        if (fileExists(file.getFileId()) || fileExists(file.getRemotePath())) {
            // 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());
        }
    }
    // prepare operations to remove files in the given folder
    String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + "=?";
    String[] whereArgs;
    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 = createContentValueForFile(folder);
    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, 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);
    }
    // update new id in file objects for insertions
    if (results != null) {
        long newId;
        Iterator<OCFile> filesIt = updatedFiles.iterator();
        OCFile file = null;
        for (ContentProviderResult result : results) {
            if (filesIt.hasNext()) {
                file = filesIt.next();
            } else {
                file = null;
            }
            if (result.uri != null) {
                newId = Long.parseLong(result.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) RemoteFile(com.owncloud.android.lib.resources.files.RemoteFile) File(java.io.File) OperationApplicationException(android.content.OperationApplicationException)

Example 7 with ContentProviderResult

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

the class FileContentProvider method applyBatch.

@NonNull
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    Log_OC.d("FileContentProvider", "applying batch in provider " + this + " (temporary: " + isTemporary() + ")");
    ContentProviderResult[] results = new ContentProviderResult[operations.size()];
    int i = 0;
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    // it's supposed that transactions can be nested
    db.beginTransaction();
    try {
        for (ContentProviderOperation operation : operations) {
            results[i] = operation.apply(this, results, i);
            i++;
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    Log_OC.d("FileContentProvider", "applied batch in provider " + this);
    return results;
}
Also used : ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) NonNull(android.support.annotation.NonNull)

Example 8 with ContentProviderResult

use of android.content.ContentProviderResult in project orgzly-android by orgzly.

the class NotesClient method update.

/**
 * Updates note by its ID.
 */
public static int update(Context context, Note note) {
    ContentValues values = new ContentValues();
    toContentValues(values, note);
    Uri noteUri = ProviderContract.Notes.ContentUri.notesId(note.getId());
    Uri uri = noteUri.buildUpon().appendQueryParameter("bookId", String.valueOf(note.getPosition().getBookId())).build();
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    /* Update note. */
    ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
    /* Delete all note's properties. */
    ops.add(ContentProviderOperation.newDelete(ProviderContract.NoteProperties.ContentUri.notesIdProperties(note.getId())).build());
    /* Add each of the note's property. */
    int i = 0;
    OrgProperties properties = note.getHead().getProperties();
    for (String name : properties.keySet()) {
        String value = properties.get(name);
        values = new ContentValues();
        values.put(ProviderContract.NoteProperties.Param.NOTE_ID, note.getId());
        values.put(ProviderContract.NoteProperties.Param.NAME, name);
        values.put(ProviderContract.NoteProperties.Param.VALUE, value);
        values.put(ProviderContract.NoteProperties.Param.POSITION, i++);
        ops.add(ContentProviderOperation.newInsert(ProviderContract.NoteProperties.ContentUri.notesProperties()).withValues(values).build());
    }
    ContentProviderResult[] result;
    try {
        result = context.getContentResolver().applyBatch(ProviderContract.AUTHORITY, ops);
    } catch (RemoteException | OperationApplicationException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    return result[0].count;
}
Also used : ContentValues(android.content.ContentValues) ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) Uri(android.net.Uri) OrgProperties(com.orgzly.org.OrgProperties) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 9 with ContentProviderResult

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

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 10 with ContentProviderResult

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

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)

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