下面列出了怎么用android.content.OperationApplicationException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
if (operations.size() > 0) {
ContentProvider provider = getContentProvider(operations.get(0).getUri());
if (provider != null) {
try {
for (ContentProviderOperation operation : operations) {
Uri pluginUri = Uri.parse(operation.getUri().getQueryParameter(IntentConstant.EXTRA_TARGET_URI_KEY));
ReflectionUtils.on(operation).set("mUri", pluginUri);
}
return provider.applyBatch(operations);
} catch (Exception e) {
return new ContentProviderResult[0];
}
}
}
return new ContentProviderResult[0];
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
@NonNull
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
try {
Field uriField = ContentProviderOperation.class.getDeclaredField("mUri");
uriField.setAccessible(true);
for (ContentProviderOperation operation : operations) {
Uri pluginUri = Uri.parse(operation.getUri().getQueryParameter(KEY_URI));
uriField.set(operation, pluginUri);
}
} catch (Exception e) {
return new ContentProviderResult[0];
}
if (operations.size() > 0) {
ContentProvider provider = getContentProvider(operations.get(0).getUri());
if (provider != null) {
return provider.applyBatch(operations);
}
}
return new ContentProviderResult[0];
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
@Override
public ContentProviderResult[] applyBatch (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();
db.beginTransaction(); // it's supposed that transactions can be nested
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;
}
public static Uri add(ContactSpec spec) {
// original code http://stackoverflow.com/questions/4744187/how-to-add-new-contacts-in-android
// good blog http://androiddevelopement.blogspot.de/2011/07/insert-update-delete-view-contacts-in.html
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
addContactBase(ops);
addContactDisplayName(spec, ops);
addContactAddress(spec, ops);
try {
ContentProviderResult[] results = InstrumentationRegistry.getTargetContext().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
return results[0].uri;
} catch (RemoteException | OperationApplicationException e) {
throw new IllegalStateException("Could not add contact", e);
}
}
@Override
public @NonNull ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
final SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
final ContentProviderResult[] results =
super.applyBatch(operations);
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
@SuppressWarnings("UnusedReturnValue")
List<Uri> execute() {
List<Uri> resultUris = new ArrayList<>();
if (mOperations.size() == 0) {
return resultUris;
}
// Apply the mOperations to the content provider
try {
ContentProviderResult[] results = mResolver.applyBatch(ContactsContract.AUTHORITY, mOperations);
if (results.length > 0) {
for (ContentProviderResult result : results) {
resultUris.add(result.uri);
}
}
} catch (final OperationApplicationException | RemoteException e) {
Log.e(TAG, "storing contact data failed", e);
}
mOperations.clear();
return resultUris;
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@NonNull
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
public synchronized static void updateEvent(Context context, Contact contact, DateUnknownYear newBirthday) throws EventException {
// TODO UNIFORMISE
for (CalendarEvent event : getEventsSavedOrCreateNewsForEachYear(context, contact)) {
// Construct each anniversary of new birthday
int year = new DateTime(event.getDate()).getYear();
Date newBirthdayDate = DateUnknownYear.getDateWithYear(newBirthday.getDate(), year);
event.setDateStart(newBirthdayDate);
event.setAllDay(true);
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
ContentProviderOperation contentProviderOperation = EventProvider.update(event);
operations.add(contentProviderOperation);
try {
ContentProviderResult[] contentProviderResults =
context.getContentResolver().applyBatch(CalendarContract.AUTHORITY, operations);
for(ContentProviderResult contentProviderResult : contentProviderResults) {
if (contentProviderResult.count != 0)
Log.d(TAG, "Update event : " + event.toString());
}
} catch (RemoteException|OperationApplicationException e) {
Log.e(TAG, "Unable to update event : " + e.getMessage());
}
}
}
public synchronized static void deleteEventsFromContact(Context context, Contact contact) {
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
try {
for (CalendarEvent event : getEventsSavedForEachYear(context, contact)) {
operations.add(ReminderProvider.deleteAll(context, event.getId()));
operations.add(EventProvider.delete(event));
}
ContentProviderResult[] contentProviderResults =
context.getContentResolver().applyBatch(CalendarContract.AUTHORITY, operations);
for(ContentProviderResult contentProviderResult : contentProviderResults) {
Log.d(TAG, contentProviderResult.toString());
if (contentProviderResult.uri != null)
Log.d(TAG, contentProviderResult.uri.toString());
}
} catch (RemoteException |OperationApplicationException |EventException e) {
Log.e(TAG, "Unable to deleteById events : " + e.getMessage());
}
}
public static void saveInTransaction(Context context, List<? extends CPDefaultRecord> records) throws RemoteException, OperationApplicationException {
List<ContentProviderOperation> operations = prepareTransaction(context, records);
ContentProviderResult[] contentProviderResults = CPOrm.applyPreparedOperations(operations);
Map<Class, Long> referenceIds = new HashMap<>();
for (int i = 0; i < contentProviderResults.length; i++) {
ContentProviderResult result = contentProviderResults[i];
CPDefaultRecord source = records.get(i);
referenceIds.remove(source.getClass());
if(result.uri != null && source.getId() == null && ContentUris.parseId(result.uri) != -1){
source.setId(ContentUris.parseId(result.uri));
referenceIds.put(source.getClass(), source.getId());
}
try {
applyReferenceResults(source.getClass(), source, referenceIds);
} catch (IllegalAccessException e) {
CPOrmLog.e("Failed to apply back reference id's for uri " + result.uri);
}
}
}
private void insertAllNewContacts() {
// Set up a batch operation on Contacts ContentProvider
ArrayList<ContentProviderOperation> batchOperation = new ArrayList<>();
for (String name : mNames) {
addRecordToBatchInsertOperation(name, batchOperation);
}
try {
// Apply all batched operations
getContentResolver().applyBatch(ContactsContract.AUTHORITY,
batchOperation);
} catch (RemoteException | OperationApplicationException e) {
Log.i(TAG, "RemoteException");
}
}
/**
* {@inheritDoc}
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
ContentProviderResult[] result = null;
SQLiteDatabase db = this.getDatabaseHelper().getWritableDatabase();
db.beginTransaction();
try {
result = super.applyBatch(operations);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
@NonNull
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
ContentProviderResult[] result = null;
applyingBatch = true;
final SQLiteDatabase db = db();
db.beginTransaction();
try {
result = super.applyBatch(operations);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
applyingBatch = false;
}
return result;
}
private void flushApksToDbInBatch(Map<String, Long> appIds) throws IndexUpdater.UpdateException {
List<Apk> apksToSaveList = new ArrayList<>();
for (Map.Entry<String, List<Apk>> entries : apksToSave.entrySet()) {
for (Apk apk : entries.getValue()) {
apk.appId = appIds.get(apk.packageName);
}
apksToSaveList.addAll(entries.getValue());
}
calcApkCompatibilityFlags(apksToSaveList);
ArrayList<ContentProviderOperation> apkOperations = insertApks(apksToSaveList);
try {
context.getContentResolver().applyBatch(TempApkProvider.getAuthority(), apkOperations);
} catch (RemoteException | OperationApplicationException e) {
throw new IndexUpdater.UpdateException("An internal error occurred while updating the database", e);
}
}
@Override
public void execute(Context context, ContentProviderClient contentProviderClient, RowDataSnapshot<TaskContract.Instances> data, Uri taskUri) throws RemoteException, OperationApplicationException
{
try
{
RowStateInfo rsi = new RowStateInfo(data);
new NotificationPrefs(context).next()
.edit()
.putString(
taskUri.toString(),
new JSONObject()
.put("version", new TaskVersion(data).value())
.put("started", rsi.started())
.put("due", rsi.due())
.put("done", rsi.done())
.put("ongoing", rsi.pinned()).toString())
.apply();
}
catch (JSONException e)
{
throw new RuntimeException("Unable to serialize to JSON", e);
}
}
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
/**
* Test that an update that doesn't change anything doesn't trigger a notification.
*/
@Test
public void testNoOpUpdate() throws RemoteException, OperationApplicationException
{
RowSnapshot<TaskLists> taskList = new VirtualRowSnapshot<>(new LocalTaskListsTable(mAuthority));
RowSnapshot<Tasks> task = new VirtualRowSnapshot<>(new TaskListScoped(taskList, new TasksTable(mAuthority)));
OperationsQueue queue = new BasicOperationsQueue(mClient);
queue.enqueue(
new Seq<>(
new Put<>(taskList, new NameData("list1")),
new Put<>(task, new TitleData("task1"))));
queue.flush();
assertThat(new Seq<>(
new Put<>(task, new TitleData("task1"))),
notifies(
TaskContract.getContentUri(mAuthority),
queue,
// there should no notification
emptyIterable()));
}
private void applyOperationsInBatches(@NonNull ContentResolver contentResolver,
@NonNull String authority,
@NonNull List<ContentProviderOperation> operations,
int batchSize)
throws OperationApplicationException, RemoteException
{
List<List<ContentProviderOperation>> batches = Util.chunk(operations, batchSize);
for (List<ContentProviderOperation> batch : batches) {
contentResolver.applyBatch(authority, new ArrayList<>(batch));
}
}
/**
* Special function for writing an exception result at the header of
* a parcel, to be used when returning an exception from a transaction.
* exception will be re-thrown by the function in another process
* @param reply Parcel to write to
* @param e The Exception to be written.
* @see Parcel#writeNoException
* @see Parcel#writeException
*/
public static final void writeExceptionToParcel(Parcel reply, Exception e) {
int code = 0;
boolean logException = true;
if (e instanceof FileNotFoundException) {
code = 1;
logException = false;
} else if (e instanceof IllegalArgumentException) {
code = 2;
} else if (e instanceof UnsupportedOperationException) {
code = 3;
} else if (e instanceof SQLiteAbortException) {
code = 4;
} else if (e instanceof SQLiteConstraintException) {
code = 5;
} else if (e instanceof SQLiteDatabaseCorruptException) {
code = 6;
} else if (e instanceof SQLiteFullException) {
code = 7;
} else if (e instanceof SQLiteDiskIOException) {
code = 8;
} else if (e instanceof SQLiteException) {
code = 9;
} else if (e instanceof OperationApplicationException) {
code = 10;
} else if (e instanceof OperationCanceledException) {
code = 11;
logException = false;
} else {
reply.writeException(e);
Log.e(TAG, "Writing exception to parcel", e);
return;
}
reply.writeInt(code);
reply.writeString(e.getMessage());
if (logException) {
Log.e(TAG, "Writing exception to parcel", e);
}
}
public static void readExceptionWithOperationApplicationExceptionFromParcel(
Parcel reply) throws OperationApplicationException {
int code = reply.readExceptionCode();
if (code == 0) return;
String msg = reply.readString();
if (code == 10) {
throw new OperationApplicationException(msg);
} else {
DatabaseUtils.readExceptionFromParcel(reply, msg, code);
}
}
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
createDbIfNotExists();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
ContentProviderResult[] result = super.applyBatch(operations);
db.setTransactionSuccessful();
reloadLauncherIfExternal();
return result;
} finally {
db.endTransaction();
}
}
@Override
public ContentProviderResult[] applyBatch(
ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
initIfNecessary();
return super.applyBatch(operations);
}
public void saveTrendingRepositories(String period, String language,
List<TrendingRepository> repositories) {
Uri uri = TrendingContract.TrendingEntry.CONTENT_URI;
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newDelete(uri)
.withSelection(TrendingContract.TrendingEntry.COLUMN_LANGUAGE + " = ? AND " +
TrendingContract.TrendingEntry.COLUMN_PERIOD + " = ? ",
new String[]{language, period}).build());
for (TrendingRepository repository : repositories) {
repository.setLanguage(language);
repository.setPeriod(period);
ContentValues contentValues = TrendingContract.TrendingEntry
.buildContentValues(repository, period, language);
ops.add(ContentProviderOperation.newInsert(uri)
.withValues(contentValues).build());
}
try {
mContentResolver.applyBatch(TrendingContract.CONTENT_AUTHORITY, ops);
mContentResolver.notifyChange(uri, null);
} catch (RemoteException | OperationApplicationException e) {
FirebaseCrash.report(e);
}
}
@Override
public ContentProviderResult[] applyBatch(
ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
initIfNecessary();
return super.applyBatch(operations);
}
@Override
public void onPerformSync(Account account,
Bundle extras,
String authority,
ContentProviderClient provider,
SyncResult syncResult) {
Call<ManufacturersAndDevicesResponse> call = WebServiceClient
.getInstance()
.getService()
.getManufacturersAndDevices();
try {
// Perform synchronous web service call
Response<ManufacturersAndDevicesResponse> wrappedResponse =
call.execute();
ArrayList<ContentProviderOperation> operations =
generateDatabaseOperations(wrappedResponse.body());
provider.applyBatch(operations);
} catch (IOException
| OperationApplicationException
| RemoteException e) {
Log.e(TAG, "Could not perform sync", e);
}
}
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
ContentProviderResult[] result = super.applyBatch(operations);
db.setTransactionSuccessful();
reloadLauncherIfExternal();
return result;
} finally {
db.endTransaction();
}
}
/**
* Apply operations
*/
private void applyBatch() {
try {
ContentProviderResult[] contentProviderResults =
contentResolver.applyBatch(CalendarContract.AUTHORITY, ops);
for(ContentProviderResult result : contentProviderResults)
if(result.uri != null)
Log.d(this.getClass().getSimpleName(), result.uri.toString());
} catch (RemoteException|OperationApplicationException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
} finally {
ops.clear();
}
}
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
ContentProviderResult[] results = super.applyBatch(operations);
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
notifyChange();
}
}