File: ContentProviderOperation.java

package info (click to toggle)
android-platform-frameworks-base 1%3A14~beta1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 326,084 kB
  • sloc: java: 2,032,373; xml: 343,016; cpp: 304,181; python: 3,683; ansic: 2,090; sh: 1,871; makefile: 120; sed: 19
file content (1039 lines) | stat: -rw-r--r-- 39,085 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.content;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.compat.annotation.UnsupportedAppUsage;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.util.SparseArray;

import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;

/**
 * Represents a single operation to be performed as part of a batch of operations.
 *
 * @see ContentProvider#applyBatch(ArrayList)
 */
public class ContentProviderOperation implements Parcelable {
    /** @hide exposed for unit tests */
    @UnsupportedAppUsage
    public final static int TYPE_INSERT = 1;
    /** @hide exposed for unit tests */
    @UnsupportedAppUsage
    public final static int TYPE_UPDATE = 2;
    /** @hide exposed for unit tests */
    @UnsupportedAppUsage
    public final static int TYPE_DELETE = 3;
    /** @hide exposed for unit tests */
    public final static int TYPE_ASSERT = 4;
    /** @hide exposed for unit tests */
    public final static int TYPE_CALL = 5;

    @UnsupportedAppUsage
    private final int mType;
    @UnsupportedAppUsage
    private final Uri mUri;
    private final String mMethod;
    private final String mArg;
    private final ArrayMap<String, Object> mValues;
    private final ArrayMap<String, Object> mExtras;
    @UnsupportedAppUsage
    private final String mSelection;
    private final SparseArray<Object> mSelectionArgs;
    private final Integer mExpectedCount;
    private final boolean mYieldAllowed;
    private final boolean mExceptionAllowed;

    private final static String TAG = "ContentProviderOperation";

    /**
     * Creates a {@link ContentProviderOperation} by copying the contents of a
     * {@link Builder}.
     */
    private ContentProviderOperation(Builder builder) {
        mType = builder.mType;
        mUri = builder.mUri;
        mMethod = builder.mMethod;
        mArg = builder.mArg;
        mValues = builder.mValues;
        mExtras = builder.mExtras;
        mSelection = builder.mSelection;
        mSelectionArgs = builder.mSelectionArgs;
        mExpectedCount = builder.mExpectedCount;
        mYieldAllowed = builder.mYieldAllowed;
        mExceptionAllowed = builder.mExceptionAllowed;
    }

    private ContentProviderOperation(Parcel source) {
        mType = source.readInt();
        mUri = Uri.CREATOR.createFromParcel(source);
        mMethod = source.readInt() != 0 ? source.readString8() : null;
        mArg = source.readInt() != 0 ? source.readString8() : null;
        final int valuesSize = source.readInt();
        if (valuesSize != -1) {
            mValues = new ArrayMap<>(valuesSize);
            source.readArrayMap(mValues, null);
        } else {
            mValues = null;
        }
        final int extrasSize = source.readInt();
        if (extrasSize != -1) {
            mExtras = new ArrayMap<>(extrasSize);
            source.readArrayMap(mExtras, null);
        } else {
            mExtras = null;
        }
        mSelection = source.readInt() != 0 ? source.readString8() : null;
        mSelectionArgs = source.readSparseArray(null, java.lang.Object.class);
        mExpectedCount = source.readInt() != 0 ? source.readInt() : null;
        mYieldAllowed = source.readInt() != 0;
        mExceptionAllowed = source.readInt() != 0;
    }

    /** @hide */
    public ContentProviderOperation(ContentProviderOperation cpo, Uri withUri) {
        mType = cpo.mType;
        mUri = withUri;
        mMethod = cpo.mMethod;
        mArg = cpo.mArg;
        mValues = cpo.mValues;
        mExtras = cpo.mExtras;
        mSelection = cpo.mSelection;
        mSelectionArgs = cpo.mSelectionArgs;
        mExpectedCount = cpo.mExpectedCount;
        mYieldAllowed = cpo.mYieldAllowed;
        mExceptionAllowed = cpo.mExceptionAllowed;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mType);
        Uri.writeToParcel(dest, mUri);
        if (mMethod != null) {
            dest.writeInt(1);
            dest.writeString8(mMethod);
        } else {
            dest.writeInt(0);
        }
        if (mArg != null) {
            dest.writeInt(1);
            dest.writeString8(mArg);
        } else {
            dest.writeInt(0);
        }
        if (mValues != null) {
            dest.writeInt(mValues.size());
            dest.writeArrayMap(mValues);
        } else {
            dest.writeInt(-1);
        }
        if (mExtras != null) {
            dest.writeInt(mExtras.size());
            dest.writeArrayMap(mExtras);
        } else {
            dest.writeInt(-1);
        }
        if (mSelection != null) {
            dest.writeInt(1);
            dest.writeString8(mSelection);
        } else {
            dest.writeInt(0);
        }
        dest.writeSparseArray(mSelectionArgs);
        if (mExpectedCount != null) {
            dest.writeInt(1);
            dest.writeInt(mExpectedCount);
        } else {
            dest.writeInt(0);
        }
        dest.writeInt(mYieldAllowed ? 1 : 0);
        dest.writeInt(mExceptionAllowed ? 1 : 0);
    }

    /**
     * Create a {@link Builder} suitable for building an operation that will
     * invoke {@link ContentProvider#insert}.
     *
     * @param uri The {@link Uri} that is the target of the operation.
     */
    public static @NonNull Builder newInsert(@NonNull Uri uri) {
        return new Builder(TYPE_INSERT, uri);
    }

    /**
     * Create a {@link Builder} suitable for building an operation that will
     * invoke {@link ContentProvider#update}.
     *
     * @param uri The {@link Uri} that is the target of the operation.
     */
    public static @NonNull Builder newUpdate(@NonNull Uri uri) {
        return new Builder(TYPE_UPDATE, uri);
    }

    /**
     * Create a {@link Builder} suitable for building an operation that will
     * invoke {@link ContentProvider#delete}.
     *
     * @param uri The {@link Uri} that is the target of the operation.
     */
    public static @NonNull Builder newDelete(@NonNull Uri uri) {
        return new Builder(TYPE_DELETE, uri);
    }

    /**
     * Create a {@link Builder} suitable for building a
     * {@link ContentProviderOperation} to assert a set of values as provided
     * through {@link Builder#withValues(ContentValues)}.
     */
    public static @NonNull Builder newAssertQuery(@NonNull Uri uri) {
        return new Builder(TYPE_ASSERT, uri);
    }

    /**
     * Create a {@link Builder} suitable for building an operation that will
     * invoke {@link ContentProvider#call}.
     *
     * @param uri The {@link Uri} that is the target of the operation.
     */
    public static @NonNull Builder newCall(@NonNull Uri uri, @Nullable String method,
            @Nullable String arg) {
        return new Builder(TYPE_CALL, uri, method, arg);
    }

    /**
     * Gets the Uri for the target of the operation.
     */
    public @NonNull Uri getUri() {
        return mUri;
    }

    /**
     * Returns true if the operation allows yielding the database to other transactions
     * if the database is contended.
     *
     * @see android.database.sqlite.SQLiteDatabase#yieldIfContendedSafely()
     */
    public boolean isYieldAllowed() {
        return mYieldAllowed;
    }

    /**
     * Returns true if this operation allows subsequent operations to continue
     * even if this operation throws an exception. When true, any encountered
     * exception is returned via {@link ContentProviderResult#exception}.
     */
    public boolean isExceptionAllowed() {
        return mExceptionAllowed;
    }

    /** @hide exposed for unit tests */
    @UnsupportedAppUsage
    public int getType() {
        return mType;
    }

    /**
     * Returns true if the operation represents a {@link ContentProvider#insert}
     * operation.
     *
     * @see #newInsert
     */
    public boolean isInsert() {
        return mType == TYPE_INSERT;
    }

    /**
     * Returns true if the operation represents a {@link ContentProvider#delete}
     * operation.
     *
     * @see #newDelete
     */
    public boolean isDelete() {
        return mType == TYPE_DELETE;
    }

    /**
     * Returns true if the operation represents a {@link ContentProvider#update}
     * operation.
     *
     * @see #newUpdate
     */
    public boolean isUpdate() {
        return mType == TYPE_UPDATE;
    }

    /**
     * Returns true if the operation represents an assert query.
     *
     * @see #newAssertQuery
     */
    public boolean isAssertQuery() {
        return mType == TYPE_ASSERT;
    }

    /**
     * Returns true if the operation represents a {@link ContentProvider#call}
     * operation.
     *
     * @see #newCall
     */
    public boolean isCall() {
        return mType == TYPE_CALL;
    }

    /**
     * Returns true if the operation represents an insertion, deletion, or update.
     *
     * @see #isInsert
     * @see #isDelete
     * @see #isUpdate
     */
    public boolean isWriteOperation() {
        return mType == TYPE_DELETE || mType == TYPE_INSERT || mType == TYPE_UPDATE;
    }

    /**
     * Returns true if the operation represents an assert query.
     *
     * @see #isAssertQuery
     */
    public boolean isReadOperation() {
        return mType == TYPE_ASSERT;
    }

    /**
     * Applies this operation using the given provider. The backRefs array is used to resolve any
     * back references that were requested using
     * {@link Builder#withValueBackReferences(ContentValues)} and
     * {@link Builder#withSelectionBackReference}.
     * @param provider the {@link ContentProvider} on which this batch is applied
     * @param backRefs a {@link ContentProviderResult} array that will be consulted
     * to resolve any requested back references.
     * @param numBackRefs the number of valid results on the backRefs array.
     * @return a {@link ContentProviderResult} that contains either the {@link Uri} of the inserted
     * row if this was an insert otherwise the number of rows affected.
     * @throws OperationApplicationException thrown if either the insert fails or
     * if the number of rows affected didn't match the expected count
     */
    public @NonNull ContentProviderResult apply(@NonNull ContentProvider provider,
            @NonNull ContentProviderResult[] backRefs, int numBackRefs)
            throws OperationApplicationException {
        if (mExceptionAllowed) {
            try {
                return applyInternal(provider, backRefs, numBackRefs);
            } catch (Exception e) {
                return new ContentProviderResult(e);
            }
        } else {
            return applyInternal(provider, backRefs, numBackRefs);
        }
    }

    private ContentProviderResult applyInternal(ContentProvider provider,
            ContentProviderResult[] backRefs, int numBackRefs)
            throws OperationApplicationException {
        final ContentValues values = resolveValueBackReferences(backRefs, numBackRefs);

        // If the creator requested explicit selection or selectionArgs, it
        // should take precedence over similar values they defined in extras
        Bundle extras = resolveExtrasBackReferences(backRefs, numBackRefs);
        if (mSelection != null) {
            extras = (extras != null) ? extras : new Bundle();
            extras.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, mSelection);
        }
        if (mSelectionArgs != null) {
            extras = (extras != null) ? extras : new Bundle();
            extras.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS,
                    resolveSelectionArgsBackReferences(backRefs, numBackRefs));
        }

        if (mType == TYPE_INSERT) {
            final Uri newUri = provider.insert(mUri, values, extras);
            if (newUri != null) {
                return new ContentProviderResult(newUri);
            } else {
                throw new OperationApplicationException(
                        "Insert into " + mUri + " returned no result");
            }
        } else if (mType == TYPE_CALL) {
            final Bundle res = provider.call(mUri.getAuthority(), mMethod, mArg, extras);
            return new ContentProviderResult(res);
        }

        final int numRows;
        if (mType == TYPE_DELETE) {
            numRows = provider.delete(mUri, extras);
        } else if (mType == TYPE_UPDATE) {
            numRows = provider.update(mUri, values, extras);
        } else if (mType == TYPE_ASSERT) {
            // Assert that all rows match expected values
            String[] projection =  null;
            if (values != null) {
                // Build projection map from expected values
                final ArrayList<String> projectionList = new ArrayList<String>();
                for (Map.Entry<String, Object> entry : values.valueSet()) {
                    projectionList.add(entry.getKey());
                }
                projection = projectionList.toArray(new String[projectionList.size()]);
            }
            final Cursor cursor = provider.query(mUri, projection, extras, null);
            try {
                numRows = cursor.getCount();
                if (projection != null) {
                    while (cursor.moveToNext()) {
                        for (int i = 0; i < projection.length; i++) {
                            final String cursorValue = cursor.getString(i);
                            final String expectedValue = values.getAsString(projection[i]);
                            if (!TextUtils.equals(cursorValue, expectedValue)) {
                                // Throw exception when expected values don't match
                                throw new OperationApplicationException("Found value " + cursorValue
                                        + " when expected " + expectedValue + " for column "
                                        + projection[i]);
                            }
                        }
                    }
                }
            } finally {
                cursor.close();
            }
        } else {
            throw new IllegalStateException("bad type, " + mType);
        }

        if (mExpectedCount != null && mExpectedCount != numRows) {
            throw new OperationApplicationException(
                    "Expected " + mExpectedCount + " rows but actual " + numRows);
        }

        return new ContentProviderResult(numRows);
    }

    /**
     * Return the values for this operation after resolving any requested
     * back-references using the given results.
     *
     * @param backRefs the results to use when resolving any back-references
     * @param numBackRefs the number of results which are valid
     */
    public @Nullable ContentValues resolveValueBackReferences(
            @NonNull ContentProviderResult[] backRefs, int numBackRefs) {
        if (mValues != null) {
            final ContentValues values = new ContentValues();
            for (int i = 0; i < mValues.size(); i++) {
                final Object value = mValues.valueAt(i);
                final Object resolved;
                if (value instanceof BackReference) {
                    resolved = ((BackReference) value).resolve(backRefs, numBackRefs);
                } else {
                    resolved = value;
                }
                values.putObject(mValues.keyAt(i), resolved);
            }
            return values;
        } else {
            return null;
        }
    }

    /**
     * Return the extras for this operation after resolving any requested
     * back-references using the given results.
     *
     * @param backRefs the results to use when resolving any back-references
     * @param numBackRefs the number of results which are valid
     */
    public @Nullable Bundle resolveExtrasBackReferences(
            @NonNull ContentProviderResult[] backRefs, int numBackRefs) {
        if (mExtras != null) {
            final Bundle extras = new Bundle();
            for (int i = 0; i < mExtras.size(); i++) {
                final Object value = mExtras.valueAt(i);
                final Object resolved;
                if (value instanceof BackReference) {
                    resolved = ((BackReference) value).resolve(backRefs, numBackRefs);
                } else {
                    resolved = value;
                }
                extras.putObject(mExtras.keyAt(i), resolved);
            }
            return extras;
        } else {
            return null;
        }
    }

    /**
     * Return the selection arguments for this operation after resolving any
     * requested back-references using the given results.
     *
     * @param backRefs the results to use when resolving any back-references
     * @param numBackRefs the number of results which are valid
     */
    public @Nullable String[] resolveSelectionArgsBackReferences(
            @NonNull ContentProviderResult[] backRefs, int numBackRefs) {
        if (mSelectionArgs != null) {
            int max = -1;
            for (int i = 0; i < mSelectionArgs.size(); i++) {
                max = Math.max(max, mSelectionArgs.keyAt(i));
            }

            final String[] selectionArgs = new String[max + 1];
            for (int i = 0; i < mSelectionArgs.size(); i++) {
                final Object value = mSelectionArgs.valueAt(i);
                final Object resolved;
                if (value instanceof BackReference) {
                    resolved = ((BackReference) value).resolve(backRefs, numBackRefs);
                } else {
                    resolved = value;
                }
                selectionArgs[mSelectionArgs.keyAt(i)] = String.valueOf(resolved);
            }
            return selectionArgs;
        } else {
            return null;
        }
    }

    /** {@hide} */
    public static String typeToString(int type) {
        switch (type) {
            case TYPE_INSERT: return "insert";
            case TYPE_UPDATE: return "update";
            case TYPE_DELETE: return "delete";
            case TYPE_ASSERT: return "assert";
            case TYPE_CALL: return "call";
            default: return Integer.toString(type);
        }
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("ContentProviderOperation(");
        sb.append("type=").append(typeToString(mType)).append(' ');
        if (mUri != null) {
            sb.append("uri=").append(mUri).append(' ');
        }
        if (mValues != null) {
            sb.append("values=").append(mValues).append(' ');
        }
        if (mSelection != null) {
            sb.append("selection=").append(mSelection).append(' ');
        }
        if (mSelectionArgs != null) {
            sb.append("selectionArgs=").append(mSelectionArgs).append(' ');
        }
        if (mExpectedCount != null) {
            sb.append("expectedCount=").append(mExpectedCount).append(' ');
        }
        if (mYieldAllowed) {
            sb.append("yieldAllowed ");
        }
        if (mExceptionAllowed) {
            sb.append("exceptionAllowed ");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(")");
        return sb.toString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final @android.annotation.NonNull Creator<ContentProviderOperation> CREATOR =
            new Creator<ContentProviderOperation>() {
        @Override
        public ContentProviderOperation createFromParcel(Parcel source) {
            return new ContentProviderOperation(source);
        }

        @Override
        public ContentProviderOperation[] newArray(int size) {
            return new ContentProviderOperation[size];
        }
    };

    /** {@hide} */
    public static class BackReference implements Parcelable {
        private final int fromIndex;
        private final String fromKey;

        private BackReference(int fromIndex, String fromKey) {
            this.fromIndex = fromIndex;
            this.fromKey = fromKey;
        }

        public BackReference(Parcel src) {
            this.fromIndex = src.readInt();
            if (src.readInt() != 0) {
                this.fromKey = src.readString8();
            } else {
                this.fromKey = null;
            }
        }

        public Object resolve(ContentProviderResult[] backRefs, int numBackRefs) {
            if (fromIndex >= numBackRefs) {
                Log.e(TAG, this.toString());
                throw new ArrayIndexOutOfBoundsException("asked for back ref " + fromIndex
                        + " but there are only " + numBackRefs + " back refs");
            }
            ContentProviderResult backRef = backRefs[fromIndex];
            Object backRefValue;
            if (backRef.extras != null) {
                backRefValue = backRef.extras.get(fromKey);
            } else if (backRef.uri != null) {
                backRefValue = ContentUris.parseId(backRef.uri);
            } else {
                backRefValue = (long) backRef.count;
            }
            return backRefValue;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(fromIndex);
            if (fromKey != null) {
                dest.writeInt(1);
                dest.writeString8(fromKey);
            } else {
                dest.writeInt(0);
            }
        }

        @Override
        public int describeContents() {
            return 0;
        }

        public static final @android.annotation.NonNull Creator<BackReference> CREATOR =
                new Creator<BackReference>() {
            @Override
            public BackReference createFromParcel(Parcel source) {
                return new BackReference(source);
            }

            @Override
            public BackReference[] newArray(int size) {
                return new BackReference[size];
            }
        };
    }

    /**
     * Used to add parameters to a {@link ContentProviderOperation}. The {@link Builder} is
     * first created by calling {@link ContentProviderOperation#newInsert(android.net.Uri)},
     * {@link ContentProviderOperation#newUpdate(android.net.Uri)},
     * {@link ContentProviderOperation#newDelete(android.net.Uri)} or
     * {@link ContentProviderOperation#newAssertQuery(Uri)}. The withXXX methods
     * can then be used to add parameters to the builder. See the specific methods to find for
     * which {@link Builder} type each is allowed. Call {@link #build} to create the
     * {@link ContentProviderOperation} once all the parameters have been supplied.
     */
    public static class Builder {
        private final int mType;
        private final Uri mUri;
        private final String mMethod;
        private final String mArg;
        private ArrayMap<String, Object> mValues;
        private ArrayMap<String, Object> mExtras;
        private String mSelection;
        private SparseArray<Object> mSelectionArgs;
        private Integer mExpectedCount;
        private boolean mYieldAllowed;
        private boolean mExceptionAllowed;

        private Builder(int type, Uri uri) {
            this(type, uri, null, null);
        }

        private Builder(int type, Uri uri, String method, String arg) {
            mType = type;
            mUri = Objects.requireNonNull(uri);
            mMethod = method;
            mArg = arg;
        }

        /** Create a ContentProviderOperation from this {@link Builder}. */
        public @NonNull ContentProviderOperation build() {
            if (mType == TYPE_UPDATE) {
                if ((mValues == null || mValues.isEmpty())) {
                    throw new IllegalArgumentException("Empty values");
                }
            }
            if (mType == TYPE_ASSERT) {
                if ((mValues == null || mValues.isEmpty())
                        && (mExpectedCount == null)) {
                    throw new IllegalArgumentException("Empty values");
                }
            }
            return new ContentProviderOperation(this);
        }

        private void ensureValues() {
            if (mValues == null) {
                mValues = new ArrayMap<>();
            }
        }

        private void ensureExtras() {
            if (mExtras == null) {
                mExtras = new ArrayMap<>();
            }
        }

        private void ensureSelectionArgs() {
            if (mSelectionArgs == null) {
                mSelectionArgs = new SparseArray<>();
            }
        }

        private void setValue(@NonNull String key, @NonNull Object value) {
            ensureValues();
            final boolean oldReference = mValues.get(key) instanceof BackReference;
            final boolean newReference = value instanceof BackReference;
            if (!oldReference || newReference) {
                mValues.put(key, value);
            }
        }

        private void setExtra(@NonNull String key, @NonNull Object value) {
            ensureExtras();
            final boolean oldReference = mExtras.get(key) instanceof BackReference;
            final boolean newReference = value instanceof BackReference;
            if (!oldReference || newReference) {
                mExtras.put(key, value);
            }
        }

        private void setSelectionArg(int index, @NonNull Object value) {
            ensureSelectionArgs();
            final boolean oldReference = mSelectionArgs.get(index) instanceof BackReference;
            final boolean newReference = value instanceof BackReference;
            if (!oldReference || newReference) {
                mSelectionArgs.put(index, value);
            }
        }

        /**
         * Configure the values to use for this operation. This method will
         * replace any previously defined values for the contained keys, but it
         * will not replace any back-reference requests.
         * <p>
         * Any value may be dynamically overwritten using the result of a
         * previous operation by using methods such as
         * {@link #withValueBackReference(String, int)}.
         */
        public @NonNull Builder withValues(@NonNull ContentValues values) {
            assertValuesAllowed();
            ensureValues();
            final ArrayMap<String, Object> rawValues = values.getValues();
            for (int i = 0; i < rawValues.size(); i++) {
                setValue(rawValues.keyAt(i), rawValues.valueAt(i));
            }
            return this;
        }

        /**
         * Configure the given value to use for this operation. This method will
         * replace any previously defined value for this key.
         *
         * @param key the key indicating which value to configure
         */
        public @NonNull Builder withValue(@NonNull String key, @Nullable Object value) {
            assertValuesAllowed();
            if (!ContentValues.isSupportedValue(value)) {
                throw new IllegalArgumentException("bad value type: " + value.getClass().getName());
            }
            setValue(key, value);
            return this;
        }

        /**
         * Configure the given values to be dynamically overwritten using the
         * result of a previous operation. This method will replace any
         * previously defined values for these keys.
         *
         * @param backReferences set of values where the key indicates which
         *            value to configure and the value the index indicating
         *            which historical {@link ContentProviderResult} should
         *            overwrite the value
         */
        public @NonNull Builder withValueBackReferences(@NonNull ContentValues backReferences) {
            assertValuesAllowed();
            final ArrayMap<String, Object> rawValues = backReferences.getValues();
            for (int i = 0; i < rawValues.size(); i++) {
                setValue(rawValues.keyAt(i),
                        new BackReference((int) rawValues.valueAt(i), null));
            }
            return this;
        }

        /**
         * Configure the given value to be dynamically overwritten using the
         * result of a previous operation. This method will replace any
         * previously defined value for this key.
         *
         * @param key the key indicating which value to configure
         * @param fromIndex the index indicating which historical
         *            {@link ContentProviderResult} should overwrite the value
         */
        public @NonNull Builder withValueBackReference(@NonNull String key, int fromIndex) {
            assertValuesAllowed();
            setValue(key, new BackReference(fromIndex, null));
            return this;
        }

        /**
         * Configure the given value to be dynamically overwritten using the
         * result of a previous operation. This method will replace any
         * previously defined value for this key.
         *
         * @param key the key indicating which value to configure
         * @param fromIndex the index indicating which historical
         *            {@link ContentProviderResult} should overwrite the value
         * @param fromKey the key of indicating which
         *            {@link ContentProviderResult#extras} value should
         *            overwrite the value
         */
        public @NonNull Builder withValueBackReference(@NonNull String key, int fromIndex,
                @NonNull String fromKey) {
            assertValuesAllowed();
            setValue(key, new BackReference(fromIndex, fromKey));
            return this;
        }

        /**
         * Configure the extras to use for this operation. This method will
         * replace any previously defined values for the contained keys, but it
         * will not replace any back-reference requests.
         * <p>
         * Any value may be dynamically overwritten using the result of a
         * previous operation by using methods such as
         * {@link #withExtraBackReference(String, int)}.
         */
        public @NonNull Builder withExtras(@NonNull Bundle extras) {
            assertExtrasAllowed();
            ensureExtras();
            for (String key : extras.keySet()) {
                setExtra(key, extras.get(key));
            }
            return this;
        }

        /**
         * Configure the given extra to use for this operation. This method will
         * replace any previously defined extras for this key.
         *
         * @param key the key indicating which extra to configure
         */
        public @NonNull Builder withExtra(@NonNull String key, @Nullable Object value) {
            assertExtrasAllowed();
            setExtra(key, value);
            return this;
        }

        /**
         * Configure the given extra to be dynamically overwritten using the
         * result of a previous operation. This method will replace any
         * previously defined extras for this key.
         *
         * @param key the key indicating which extra to configure
         * @param fromIndex the index indicating which historical
         *            {@link ContentProviderResult} should overwrite the extra
         */
        public @NonNull Builder withExtraBackReference(@NonNull String key, int fromIndex) {
            assertExtrasAllowed();
            setExtra(key, new BackReference(fromIndex, null));
            return this;
        }

        /**
         * Configure the given extra to be dynamically overwritten using the
         * result of a previous operation. This method will replace any
         * previously defined extras for this key.
         *
         * @param key the key indicating which extra to configure
         * @param fromIndex the index indicating which historical
         *            {@link ContentProviderResult} should overwrite the extra
         * @param fromKey the key of indicating which
         *            {@link ContentProviderResult#extras} value should
         *            overwrite the extra
         */
        public @NonNull Builder withExtraBackReference(@NonNull String key, int fromIndex,
                @NonNull String fromKey) {
            assertExtrasAllowed();
            setExtra(key, new BackReference(fromIndex, fromKey));
            return this;
        }

        /**
         * Configure the selection and selection arguments to use for this
         * operation. This method will replace any previously defined selection
         * and selection arguments, but it will not replace any back-reference
         * requests.
         * <p>
         * An occurrence of {@code ?} in the selection will be replaced with the
         * corresponding selection argument when the operation is executed.
         * <p>
         * Any selection argument may be dynamically overwritten using the
         * result of a previous operation by using methods such as
         * {@link #withSelectionBackReference(int, int)}.
         */
        public @NonNull Builder withSelection(@Nullable String selection,
                @Nullable String[] selectionArgs) {
            assertSelectionAllowed();
            mSelection = selection;
            if (selectionArgs != null) {
                ensureSelectionArgs();
                for (int i = 0; i < selectionArgs.length; i++) {
                    setSelectionArg(i, selectionArgs[i]);
                }
            }
            return this;
        }

        /**
         * Configure the given selection argument to be dynamically overwritten
         * using the result of a previous operation. This method will replace
         * any previously defined selection argument at this index.
         *
         * @param index the index indicating which selection argument to
         *            configure
         * @param fromIndex the index indicating which historical
         *            {@link ContentProviderResult} should overwrite the
         *            selection argument
         */
        public @NonNull Builder withSelectionBackReference(int index, int fromIndex) {
            assertSelectionAllowed();
            setSelectionArg(index, new BackReference(fromIndex, null));
            return this;
        }

        /**
         * Configure the given selection argument to be dynamically overwritten
         * using the result of a previous operation. This method will replace
         * any previously defined selection argument at this index.
         *
         * @param index the index indicating which selection argument to
         *            configure
         * @param fromIndex the index indicating which historical
         *            {@link ContentProviderResult} should overwrite the
         *            selection argument
         * @param fromKey the key of indicating which
         *            {@link ContentProviderResult#extras} value should
         *            overwrite the selection argument
         */
        public @NonNull Builder withSelectionBackReference(int index, int fromIndex,
                @NonNull String fromKey) {
            assertSelectionAllowed();
            setSelectionArg(index, new BackReference(fromIndex, fromKey));
            return this;
        }

        /**
         * If set then if the number of rows affected by this operation does not match
         * this count {@link OperationApplicationException} will be throw.
         * This can only be used with builders of type update, delete, or assert.
         * @return this builder, to allow for chaining.
         */
        public @NonNull Builder withExpectedCount(int count) {
            if (mType != TYPE_UPDATE && mType != TYPE_DELETE && mType != TYPE_ASSERT) {
                throw new IllegalArgumentException(
                        "only updates, deletes, and asserts can have expected counts");
            }
            mExpectedCount = count;
            return this;
        }

        /**
         * If set to true then the operation allows yielding the database to other transactions
         * if the database is contended.
         * @return this builder, to allow for chaining.
         * @see android.database.sqlite.SQLiteDatabase#yieldIfContendedSafely()
         */
        public @NonNull Builder withYieldAllowed(boolean yieldAllowed) {
            mYieldAllowed = yieldAllowed;
            return this;
        }

        /**
         * If set to true, this operation allows subsequent operations to
         * continue even if this operation throws an exception. When true, any
         * encountered exception is returned via
         * {@link ContentProviderResult#exception}.
         */
        public @NonNull Builder withExceptionAllowed(boolean exceptionAllowed) {
            mExceptionAllowed = exceptionAllowed;
            return this;
        }

        /** {@hide} */
        public @NonNull Builder withFailureAllowed(boolean failureAllowed) {
            return withExceptionAllowed(failureAllowed);
        }

        private void assertValuesAllowed() {
            switch (mType) {
                case TYPE_INSERT:
                case TYPE_UPDATE:
                case TYPE_ASSERT:
                    break;
                default:
                    throw new IllegalArgumentException(
                            "Values not supported for " + typeToString(mType));
            }
        }

        private void assertSelectionAllowed() {
            switch (mType) {
                case TYPE_UPDATE:
                case TYPE_DELETE:
                case TYPE_ASSERT:
                    break;
                default:
                    throw new IllegalArgumentException(
                            "Selection not supported for " + typeToString(mType));
            }
        }

        private void assertExtrasAllowed() {
            switch (mType) {
                case TYPE_INSERT:
                case TYPE_UPDATE:
                case TYPE_DELETE:
                case TYPE_ASSERT:
                case TYPE_CALL:
                    break;
                default:
                    throw new IllegalArgumentException(
                            "Extras not supported for " + typeToString(mType));
            }
        }
    }
}