-
Notifications
You must be signed in to change notification settings - Fork 21
/
StoreLocalRepository.java
2088 lines (1852 loc) · 104 KB
/
StoreLocalRepository.java
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
/*
* Copyright 2018 Kaushik N. Sanji
*
* 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:https://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 com.example.kaushiknsanji.storeapp.data.local;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import android.support.v4.util.Pair;
import com.example.kaushiknsanji.storeapp.R;
import com.example.kaushiknsanji.storeapp.data.DataRepository;
import com.example.kaushiknsanji.storeapp.data.local.contracts.ProductContract;
import com.example.kaushiknsanji.storeapp.data.local.contracts.SalesContract;
import com.example.kaushiknsanji.storeapp.data.local.contracts.SupplierContract;
import com.example.kaushiknsanji.storeapp.data.local.models.Product;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductAttribute;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductImage;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductLite;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductSupplierInfo;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductSupplierSales;
import com.example.kaushiknsanji.storeapp.data.local.models.Supplier;
import com.example.kaushiknsanji.storeapp.data.local.models.SupplierContact;
import com.example.kaushiknsanji.storeapp.data.local.utils.QueryArgsUtility;
import com.example.kaushiknsanji.storeapp.data.local.utils.SqliteUtility;
import com.example.kaushiknsanji.storeapp.utils.AppExecutors;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static com.example.kaushiknsanji.storeapp.data.local.utils.SqliteUtility.AND;
import static com.example.kaushiknsanji.storeapp.data.local.utils.SqliteUtility.EQUALS;
import static com.example.kaushiknsanji.storeapp.data.local.utils.SqliteUtility.PLACEHOLDER;
/**
* The Database Repository class that implements {@link DataRepository} interface
* to manage communication with the Database of the App.
*
* @author Kaushik N Sanji
*/
public class StoreLocalRepository implements DataRepository {
//Constant used for logs
private static final String LOG_TAG = StoreLocalRepository.class.getSimpleName();
//Singleton instance of StoreLocalRepository
private static volatile StoreLocalRepository INSTANCE;
//The ContentResolver instance to communicate with the Database
private final ContentResolver mContentResolver;
//AppExecutors instance for threading requests
private final AppExecutors mAppExecutors;
/**
* Private Constructor of {@link StoreLocalRepository}
*
* @param contentResolver The {@link ContentResolver} instance to communicate with the Database
* @param appExecutors {@link AppExecutors} instance for threading requests
*/
private StoreLocalRepository(@NonNull ContentResolver contentResolver, @NonNull AppExecutors appExecutors) {
mContentResolver = contentResolver;
mAppExecutors = appExecutors;
}
/**
* Singleton Constructor that creates a single instance of {@link StoreLocalRepository}
*
* @param contentResolver The {@link ContentResolver} instance to communicate with the Database
* @param appExecutors {@link AppExecutors} instance for threading requests
* @return New or existing instance of {@link StoreLocalRepository}
*/
public static StoreLocalRepository getInstance(@NonNull ContentResolver contentResolver, @NonNull AppExecutors appExecutors) {
if (INSTANCE == null) {
//When instance is not available
synchronized (StoreLocalRepository.class) {
//Apply lock and check for the instance again
if (INSTANCE == null) {
//When there is no instance, create a new one
INSTANCE = new StoreLocalRepository(contentResolver, appExecutors);
}
}
}
//Returning the instance of StoreLocalRepository
return INSTANCE;
}
/**
* Method that retrieves the Categories for configuring a Product.
*
* @param queryCallback The Callback to be implemented by the caller to receive the results
*/
@Override
public void getAllCategories(@NonNull GetQueryCallback<List<String>> queryCallback) {
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Retrieving the cursor to the records, sorted by "category_name" column
Cursor cursor = mContentResolver.query(
ProductContract.ProductCategory.CONTENT_URI,
QueryArgsUtility.CategoriesQuery.getProjection(),
null,
null,
ProductContract.ProductCategory.COLUMN_ITEM_CATEGORY_NAME
);
//Iterating over the cursor records to build the list of categories
ArrayList<String> categoryList = new ArrayList<>();
try {
if (cursor != null && cursor.getCount() > 0) {
//When the query returned results
//Iterating over the cursor results and building the list of categories
while (cursor.moveToNext()) {
categoryList.add(cursor.getString(QueryArgsUtility.CategoriesQuery.COLUMN_ITEM_CATEGORY_NAME_INDEX));
}
}
} finally {
//Closing the cursor to release its resources
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
//Executing on the Main Thread
mAppExecutors.getMainThread().execute(() -> {
if (categoryList.size() > 0) {
//Pass the results to the callback
queryCallback.onResults(categoryList);
} else {
//Return to the caller when there are no results
queryCallback.onEmpty();
}
});
});
}
/**
* Method that retrieves the Category Id for the Category Name configured for the Product.
*
* @param categoryName The Category Name selected for the Product
* @param queryCallback The Callback to be implemented by the caller to receive the result.
*/
@Override
public void getCategoryByName(@NonNull String categoryName, @NonNull GetQueryCallback<Integer> queryCallback) {
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Retrieving the cursor to the record
Cursor cursor = mContentResolver.query(
ProductContract.ProductCategory.buildCategoryNameUri(categoryName),
QueryArgsUtility.CategoryByNameQuery.getProjection(),
null,
null,
null
);
//Retrieving the Category Id from the cursor
try {
if (cursor != null && cursor.moveToFirst()) {
//When Cursor is not Null and there is a record for the Category being queried
//Read the Category ID column
final Integer categoryId = cursor.getInt(QueryArgsUtility.CategoryByNameQuery.COLUMN_ITEM_CATEGORY_ID_INDEX);
//Checking if the value in the column is NULL
final boolean cursorNull = cursor.isNull(QueryArgsUtility.CategoryByNameQuery.COLUMN_ITEM_CATEGORY_ID_INDEX);
//Executing on the Main Thread
mAppExecutors.getMainThread().execute(() -> {
if (cursorNull) {
//Category ID cannot be Null. Pass the error to the callback.
queryCallback.onFailure(R.string.product_config_category_null_error, categoryName);
} else {
//When Category ID is not Null, pass the results to the callback
queryCallback.onResults(categoryId);
}
});
} else {
//When Cursor is Null, the Category being queried is not found.
//Pass the empty result to the callback in this case.
queryCallback.onEmpty();
}
} finally {
//Closing the cursor to release its resources
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
});
}
/**
* Method that retrieves the Product Details of Product identified by its Id.
*
* @param productId The Integer Id of the Product to lookup for.
* @param queryCallback The Callback to be implemented by the caller to receive the result.
*/
@Override
public void getProductDetailsById(int productId, @NonNull GetQueryCallback<Product> queryCallback) {
//Retrieving the Product details for the Product ID passed
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Retrieving the cursor to the record
Cursor cursor = mContentResolver.query(
ContentUris.withAppendedId(ProductContract.Product.CONTENT_URI, productId),
QueryArgsUtility.ItemByIdQuery.getProjection(),
null,
null,
null
);
//Retrieving item details from the cursor
try {
if (cursor != null && cursor.moveToFirst()) {
//When Cursor is not Null and there is a record for the Product being queried
//Retrieving the details of the Item
int itemId = cursor.getInt(QueryArgsUtility.ItemByIdQuery.COLUMN_ITEM_ID_INDEX);
String itemName = cursor.getString(QueryArgsUtility.ItemByIdQuery.COLUMN_ITEM_NAME_INDEX);
String itemSku = cursor.getString(QueryArgsUtility.ItemByIdQuery.COLUMN_ITEM_SKU_INDEX);
String itemDescription = cursor.getString(QueryArgsUtility.ItemByIdQuery.COLUMN_ITEM_DESCRIPTION_INDEX);
String itemCategoryName = cursor.getString(QueryArgsUtility.ItemByIdQuery.COLUMN_ITEM_CATEGORY_NAME_INDEX);
//Retrieving the Hang-off table data: START
//Retrieving the ProductAttribute for the Product ID passed
ArrayList<ProductAttribute> productAttributes = getProductAttributesById(productId);
//Retrieving the ProductImage for the Product ID passed
ArrayList<ProductImage> productImages = getProductImagesById(productId);
//Retrieving the Hang-off table data: END
//Building the Product details
final Product product = new Product.Builder()
.setId(itemId)
.setName(itemName)
.setSku(itemSku)
.setDescription(itemDescription)
.setCategory(itemCategoryName)
.setProductAttributes(productAttributes)
.setProductImages(productImages)
.createProduct();
//Executing on the Main Thread
mAppExecutors.getMainThread().execute(() -> {
//Pass the Product data to the callback
queryCallback.onResults(product);
});
} else {
//When Cursor is Null, the Product being queried is not found
//Pass the Product Not Found error to the callback in this case.
queryCallback.onFailure(R.string.product_config_no_product_found_error, productId);
}
} finally {
//Closing the cursor to release its resources
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
});
}
/**
* Method that retrieves the list of {@link ProductImage}s for the Product identified by its Id.
* This is called on the Disk Thread.
*
* @param productId The Integer Id of the Product to lookup for.
* @return List of {@link ProductImage}s for the Product identified by its Id.
*/
@WorkerThread
private ArrayList<ProductImage> getProductImagesById(int productId) {
//Retrieving the cursor to the records
Cursor cursor = mContentResolver.query(
ContentUris.withAppendedId(ProductContract.ProductImage.CONTENT_URI, productId),
QueryArgsUtility.ItemImagesQuery.getProjection(),
null,
null,
null
);
//Retrieving item images from the cursor
ArrayList<ProductImage> productImages = new ArrayList<>();
try {
if (cursor != null && cursor.getCount() > 0) {
//When the query returned results
while (cursor.moveToNext()) {
//Retrieving the values from the record pointed to by the Cursor
String imageUri = cursor.getString(QueryArgsUtility.ItemImagesQuery.COLUMN_ITEM_IMAGE_URI_INDEX);
int defaultImageId = cursor.getInt(QueryArgsUtility.ItemImagesQuery.COLUMN_ITEM_IMAGE_DEFAULT_INDEX);
//Preparing the ProductImage
ProductImage productImage = new ProductImage.Builder()
.setImageUri(imageUri)
.setIsDefault(defaultImageId == ProductContract.ProductImage.ITEM_IMAGE_DEFAULT)
.createProductImage();
//Adding to the list of ProductImages
productImages.add(productImage);
}
}
} finally {
//Closing the cursor to release its resources
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
//Returning the ProductImages retrieved for the Product ID passed
return productImages;
}
/**
* Method that retrieves the list of {@link ProductAttribute}s for the Product identified by its Id.
* This is called on the Disk Thread.
*
* @param productId The Integer Id of the Product to lookup for.
* @return List of {@link ProductAttribute}s for the Product identified by its Id.
*/
@WorkerThread
private ArrayList<ProductAttribute> getProductAttributesById(int productId) {
//Retrieving the cursor to the records
Cursor cursor = mContentResolver.query(
ContentUris.withAppendedId(ProductContract.ProductAttribute.CONTENT_URI, productId),
QueryArgsUtility.ItemAttributesQuery.getProjection(),
null,
null,
null
);
//Retrieving item attributes from the cursor
ArrayList<ProductAttribute> productAttributes = new ArrayList<>();
try {
if (cursor != null && cursor.getCount() > 0) {
//When the query returned results
while (cursor.moveToNext()) {
//Retrieving the values from the record pointed to by the Cursor
String attrName = cursor.getString(QueryArgsUtility.ItemAttributesQuery.COLUMN_ITEM_ATTR_NAME_INDEX);
String attrValue = cursor.getString(QueryArgsUtility.ItemAttributesQuery.COLUMN_ITEM_ATTR_VALUE_INDEX);
//Preparing the ProductAttribute
ProductAttribute productAttribute = new ProductAttribute.Builder()
.setAttributeName(attrName)
.setAttributeValue(attrValue)
.createProductAttribute();
//Adding to the list of ProductAttributes
productAttributes.add(productAttribute);
}
}
} finally {
//Closing the cursor to release its resources
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
//Returning the ProductAttributes retrieved for the Product ID passed
return productAttributes;
}
/**
* Method that checks and validates the uniqueness of the Product SKU {@code productSku} passed.
*
* @param productSku The Product SKU of the Product to lookup for.
* @param queryCallback The Callback to be implemented by the caller to receive the result.
*/
@Override
public void getProductSkuUniqueness(@NonNull String productSku, @NonNull GetQueryCallback<Boolean> queryCallback) {
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Retrieving the cursor to the record
Cursor cursor = mContentResolver.query(
ProductContract.Product.buildItemSkuUri(productSku),
QueryArgsUtility.ItemBySkuQuery.getProjection(),
null,
null,
null
);
//Retrieving item from the cursor
try {
//Records the uniqueness result of the SKU passed
boolean isSkuUnique;
if (cursor != null && cursor.moveToFirst()) {
//When cursor is NOT NULL
//Retrieving the Item Key for the SKU
int itemId = cursor.getInt(QueryArgsUtility.ItemBySkuQuery.COLUMN_ITEM_ID_INDEX);
//SKU is unique if the Item Key detected is null or negative
isSkuUnique = (cursor.isNull(QueryArgsUtility.ItemBySkuQuery.COLUMN_ITEM_ID_INDEX)
|| itemId < 0);
} else {
//When cursor is NULL
//SKU is unique if the query resulted in no records found
isSkuUnique = true;
}
//Recording the final data to pass to the caller
final Boolean isSkuUniqueFinal = isSkuUnique;
//Executing on the Main Thread
mAppExecutors.getMainThread().execute(() -> {
//Passing the result evaluated to the caller
queryCallback.onResults(isSkuUniqueFinal);
});
} finally {
//Closing the cursor to release its resources
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
});
}
/**
* Method that adds a New {@link Product} entry into the database table 'item'.
*
* @param newProduct The New {@link Product} to be added to the database
* @param operationsCallback The Callback to be implemented by the caller to
* receive the operation result.
*/
@Override
public void saveNewProduct(@NonNull Product newProduct, @NonNull DataOperationsCallback operationsCallback) {
//Get the Category Name
String categoryName = newProduct.getCategory();
//Check if the Category exists (Executes on Disk Thread)
getCategoryByName(categoryName, new GetQueryCallback<Integer>() {
/**
* Method invoked when the results are obtained
* for the query executed.
*
* @param categoryId The integer Category Id found for the Category Name queried
*/
@MainThread
@Override
public void onResults(Integer categoryId) {
//When Category was found
//Propagating the result to #proceedToSaveProduct
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> proceedToSaveProduct(categoryId));
}
/**
* Method invoked when there are no results
* for the query executed.
*/
@MainThread
@Override
public void onEmpty() {
//When Category does not exist, we insert the new Category to get the new record Id
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Loading the Category Name for insert
ContentValues categoryContentValues = new ContentValues();
categoryContentValues.put(ProductContract.ProductCategory.COLUMN_ITEM_CATEGORY_NAME, categoryName);
//Executing insert
Uri categoryInsertUri = mContentResolver.insert(
ProductContract.ProductCategory.CONTENT_URI,
categoryContentValues
);
//Checking the result URI
if (categoryInsertUri == null) {
//When Null, pass the error message
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> operationsCallback.onFailure(R.string.product_config_insert_category_error, categoryName));
} else {
//When NOT Null, parse for the Category Id
//Parsing the Category Id and propagating the result to #proceedToSaveProduct
proceedToSaveProduct((int) ContentUris.parseId(categoryInsertUri));
}
});
}
/**
* Method invoked when the results could not be retrieved
* for the query due to some error.
*
* @param messageId The String resource of the error message
* for the query execution failure
* @param args Variable number of arguments to replace the format specifiers
*/
@MainThread
@Override
public void onFailure(int messageId, @Nullable Object... args) {
//Pass the Failure to the callback
operationsCallback.onFailure(messageId, args);
}
/**
* Method that saves the Product details after the {@code categoryId}
* for the Product's category was determined.
*
* @param categoryId The Id of the Category determined
*/
@WorkerThread
private void proceedToSaveProduct(final int categoryId) {
//Begin to save Product data
//Loading the values for 'item' table
ContentValues itemContentValues = new ContentValues();
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_NAME, newProduct.getName());
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_SKU, newProduct.getSku());
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_DESCRIPTION, newProduct.getDescription());
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_CATEGORY_ID, categoryId);
//Executing insert
Uri itemInsertUri = mContentResolver.insert(
ProductContract.Product.CONTENT_URI,
itemContentValues
);
//Checking the result URI
if (itemInsertUri == null) {
//When Null, pass the error message
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> operationsCallback.onFailure(R.string.product_config_insert_item_error, newProduct.getName()));
} else {
//When NOT Null, parse for the Item Id
//Parsing the Uri for the Item Id
int itemId = (int) ContentUris.parseId(itemInsertUri);
//bulk insert Product Attributes
int noOfProductAttrsInserted = 0;
int noOfProductAttrsPresent = newProduct.getProductAttributes().size();
if (noOfProductAttrsPresent > 0) {
noOfProductAttrsInserted = saveProductAttributes(itemId, newProduct.getProductAttributes());
}
//bulk insert Product Images
int noOfProductImagesInserted = 0;
int noOfProductImagesPresent = newProduct.getProductImages().size();
if (noOfProductImagesPresent > 0) {
noOfProductImagesInserted = saveProductImages(itemId, newProduct.getProductImages());
}
if (noOfProductAttrsPresent == noOfProductAttrsInserted
&& noOfProductImagesPresent == noOfProductImagesInserted) {
//When the Product Hang off details were inserted successfully,
//call the operation as successful
//Executing on Main Thread
mAppExecutors.getMainThread().execute(operationsCallback::onSuccess);
} else {
//When the Product Hang off details were not inserted, pass the error message
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> operationsCallback.onFailure(R.string.product_config_insert_item_addtnl_dtls_error, newProduct.getName(), newProduct.getSku()));
}
}
}
});
}
/**
* Method that updates an existing {@link Product} entry into the database table 'item'.
*
* @param existingProduct The Existing Product details for figuring out the required
* CRUD operations
* @param newProduct The New Updated Product details to be saved in the database.
* @param operationsCallback The Callback to be implemented by the caller to
* receive the operation result.
*/
@Override
public void saveUpdatedProduct(@NonNull Product existingProduct, @NonNull Product newProduct,
@NonNull DataOperationsCallback operationsCallback) {
//Get the Category Name
String newCategoryName = newProduct.getCategory();
//Check if the Category exists (Executes on Disk Thread)
getCategoryByName(newCategoryName, new GetQueryCallback<Integer>() {
/**
* Method invoked when the results are obtained
* for the query executed.
*
* @param categoryId The integer Category Id found for the Category Name queried
*/
@MainThread
@Override
public void onResults(Integer categoryId) {
//When Category was found
//Propagating the result to #proceedToUpdateProduct
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> proceedToUpdateProduct(categoryId));
}
/**
* Method invoked when there are no results
* for the query executed.
*/
@MainThread
@Override
public void onEmpty() {
//When Category does not exist, we insert the new Category to get the new record Id
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Loading the Category Name for insert
ContentValues categoryContentValues = new ContentValues();
categoryContentValues.put(ProductContract.ProductCategory.COLUMN_ITEM_CATEGORY_NAME, newCategoryName);
//Executing insert
Uri categoryInsertUri = mContentResolver.insert(
ProductContract.ProductCategory.CONTENT_URI,
categoryContentValues
);
//Checking the result URI
if (categoryInsertUri == null) {
//When Null, pass the error message
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> operationsCallback.onFailure(R.string.product_config_update_category_error, existingProduct.getSku(), newCategoryName));
} else {
//When NOT Null, parse for the Category Id
//Parsing the Category Id and propagating the result to #proceedToUpdateProduct
proceedToUpdateProduct((int) ContentUris.parseId(categoryInsertUri));
}
});
}
/**
* Method invoked when the results could not be retrieved
* for the query due to some error.
*
* @param messageId The String resource of the error message
* for the query execution failure
* @param args Variable number of arguments to replace the format specifiers
*/
@MainThread
@Override
public void onFailure(int messageId, @Nullable Object... args) {
//Pass the Failure to the callback
operationsCallback.onFailure(messageId, args);
}
/**
* Method that updates the existing Product details after the {@code categoryId}
* for the Product's category was determined.
*
* @param categoryId The Id of the Category determined
*/
@WorkerThread
private void proceedToUpdateProduct(final int categoryId) {
//Update the Product Hang off details by inserting them completely
//(The Content Provider deletes any existing data before inserting new data)
//Get the Item Id to update
int itemId = existingProduct.getId();
//bulk insert Product Attributes
int noOfProductAttrsInserted = 0;
int noOfProductAttrsPresent = newProduct.getProductAttributes().size();
if (noOfProductAttrsPresent > 0) {
noOfProductAttrsInserted = saveProductAttributes(itemId, newProduct.getProductAttributes());
} else {
mContentResolver.delete(
ContentUris.withAppendedId(ProductContract.ProductAttribute.CONTENT_URI, existingProduct.getId()),
null,
null
);
}
//bulk insert Product Images
int noOfProductImagesInserted = 0;
int noOfProductImagesPresent = newProduct.getProductImages().size();
if (noOfProductImagesPresent > 0) {
noOfProductImagesInserted = saveProductImages(itemId, newProduct.getProductImages());
} else {
mContentResolver.delete(
ContentUris.withAppendedId(ProductContract.ProductImage.CONTENT_URI, existingProduct.getId()),
null,
null
);
}
if (noOfProductAttrsPresent == noOfProductAttrsInserted
&& noOfProductImagesPresent == noOfProductImagesInserted) {
//When the Product Hang off details were inserted successfully,
//begin with the Product update
//Compare the product details for update
boolean isNameChanged = !newProduct.getName().equals(existingProduct.getName());
boolean isSkuChanged = !newProduct.getSku().equals(existingProduct.getSku());
boolean isDescriptionChanged = !newProduct.getDescription().equals(existingProduct.getDescription());
boolean isCategoryChanged = !newProduct.getCategory().equals(existingProduct.getCategory());
if (isNameChanged || isSkuChanged || isDescriptionChanged || isCategoryChanged) {
//If any of the product details are changed, then we need to update the Product
//Loading the values for 'item' table
ContentValues itemContentValues = new ContentValues();
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_NAME, newProduct.getName());
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_SKU, newProduct.getSku());
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_DESCRIPTION, newProduct.getDescription());
itemContentValues.put(ProductContract.Product.COLUMN_ITEM_CATEGORY_ID, categoryId);
Uri contentUri = ContentUris.withAppendedId(ProductContract.Product.CONTENT_URI, itemId);
//Executing update
int noOfItemRecordsUpdated = mContentResolver.update(
contentUri,
itemContentValues,
null,
null
);
//Checking the number of records updated
if (noOfItemRecordsUpdated == 0) {
//When 0 rows were affected, pass the error message
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> operationsCallback.onFailure(R.string.product_config_update_item_error, existingProduct.getSku()));
} else if (noOfItemRecordsUpdated == 1) {
//When 1 row was affected, call the update operation as successful
//Executing on Main Thread
mAppExecutors.getMainThread().execute(operationsCallback::onSuccess);
} else if (noOfItemRecordsUpdated > 1) {
//When more than 1 row were affected, pass the error message
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> operationsCallback.onFailure(R.string.product_config_update_item_inconsistent_error, existingProduct.getSku()));
}
} else {
//When none of the Product details were changed, call the update operation as successful
//Executing on Main Thread
mAppExecutors.getMainThread().execute(operationsCallback::onSuccess);
}
} else {
//When the Product Hang off details were not inserted, pass the error message
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> operationsCallback.onFailure(R.string.product_config_update_item_addtnl_dtls_error, existingProduct.getSku()));
}
}
});
}
/**
* Method that saves the {@link ProductAttribute} details for the Product
* identified by the {@code productId} into the database table 'item_attr'.
*
* @param productId The Product Id for which the Product Attributes are to be added.
* @param productAttributes The New {@link ProductAttribute} details to be added to the database
* @return The Number of records inserted.
*/
@WorkerThread
private int saveProductAttributes(int productId, ArrayList<ProductAttribute> productAttributes) {
//Number of Product Attributes to be inserted
int noOfProductAttrsPresent = productAttributes.size();
//Preparing an array of Content values for bulk insert
ContentValues[] valuesArray = new ContentValues[noOfProductAttrsPresent];
for (int index = 0; index < noOfProductAttrsPresent; index++) {
ProductAttribute productAttribute = productAttributes.get(index);
ContentValues contentValues = new ContentValues();
contentValues.put(ProductContract.ProductAttribute.COLUMN_ITEM_ATTR_NAME, productAttribute.getAttributeName());
contentValues.put(ProductContract.ProductAttribute.COLUMN_ITEM_ATTR_VALUE, productAttribute.getAttributeValue());
valuesArray[index] = contentValues;
}
//Executing the bulk insert
return mContentResolver.bulkInsert(
ContentUris.withAppendedId(ProductContract.ProductAttribute.CONTENT_URI, productId),
valuesArray
);
}
/**
* Method that saves the {@link ProductImage} details for the Product
* identified by the {@code productId} into the database table 'item_image'.
*
* @param productId The Product Id for which the Product Images are to be added.
* @param productImages The New {@link ProductImage} details to be added to the database
* @return The Number of records inserted.
*/
@WorkerThread
private int saveProductImages(int productId, ArrayList<ProductImage> productImages) {
//Number of Product Images to be inserted
int noOfProductImagesPresent = productImages.size();
//Preparing an array of Content values for bulk insert
ContentValues[] valuesArray = new ContentValues[noOfProductImagesPresent];
for (int index = 0; index < noOfProductImagesPresent; index++) {
ProductImage productImage = productImages.get(index);
ContentValues contentValues = new ContentValues();
contentValues.put(ProductContract.ProductImage.COLUMN_ITEM_IMAGE_URI, productImage.getImageUri());
contentValues.put(ProductContract.ProductImage.COLUMN_ITEM_IMAGE_DEFAULT,
productImage.isDefault() ? ProductContract.ProductImage.ITEM_IMAGE_DEFAULT : ProductContract.ProductImage.ITEM_IMAGE_NON_DEFAULT);
valuesArray[index] = contentValues;
}
//Executing the bulk insert
return mContentResolver.bulkInsert(
ContentUris.withAppendedId(ProductContract.ProductImage.CONTENT_URI, productId),
valuesArray
);
}
/**
* Method that updates the list of {@link ProductImage} details for the
* existing Product {@code existingProduct} into the database table 'item_image'.
* Performs a silent delete operation of all the Images previously
* configured for the Product if any when the {@code productImages} passed is empty.
* (Applicable for Existing Product only)
*
* @param existingProduct The Existing Product for which the Product Images are to be updated.
* @param productImages The New List of {@link ProductImage} details to be updated to the database
* @param operationsCallback The Callback to be implemented by the caller to
* receive the operation result.
*/
@Override
public void saveProductImages(@NonNull Product existingProduct, @NonNull ArrayList<ProductImage> productImages, @NonNull DataOperationsCallback operationsCallback) {
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Bulk insert Product Images
int noOfProductImagesInserted = 0;
int noOfProductImagesPresent = productImages.size();
if (noOfProductImagesPresent > 0) {
noOfProductImagesInserted = saveProductImages(existingProduct.getId(), productImages);
} else {
mContentResolver.delete(
ContentUris.withAppendedId(ProductContract.ProductImage.CONTENT_URI, existingProduct.getId()),
null,
null
);
}
if (noOfProductImagesPresent == noOfProductImagesInserted) {
//When all the Images information were updated successfully
//Executing on Main Thread
mAppExecutors.getMainThread().execute(operationsCallback::onSuccess);
} else {
//When the Images information were NOT updated successfully
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> {
//Passing the error message to the callback
operationsCallback.onFailure(R.string.product_config_update_item_images_error, existingProduct.getSku());
});
}
});
}
/**
* Method that deletes a Product identified by its Id.
* This also deletes any relationship data with the Product.
*
* @param productId The Product Id of the Product to be deleted.
* @param operationsCallback The Callback to be implemented by the caller to
*/
@Override
public void deleteProductById(int productId, @NonNull DataOperationsCallback operationsCallback) {
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Executing Product Deletion for the Product ID passed
final int noOfRecordsDeleted = mContentResolver.delete(
ContentUris.withAppendedId(ProductContract.Product.CONTENT_URI, productId),
null,
null
);
//Executing on Main Thread
mAppExecutors.getMainThread().execute(() -> {
if (noOfRecordsDeleted > 0) {
//When some records were deleted successfully, call the delete operation as successful
operationsCallback.onSuccess();
} else {
//When no record was deleted, pass the error message
operationsCallback.onFailure(R.string.product_config_delete_item_error, productId);
}
});
});
}
/**
* Method that registers a {@link ContentObserver} class that receives callbacks
* when the data identified by a given content URI changes.
*
* @param uri The URI to watch for changes. This can be a specific row URI,
* or a base URI for a whole class of content.
* @param notifyForDescendants When false, the observer will be notified
* whenever a change occurs to the exact URI specified by
* <code>uri</code> or to one of the URI's ancestors in the path
* hierarchy. When true, the observer will also be notified
* whenever a change occurs to the URI's descendants in the path
* hierarchy.
* @param observer The {@link ContentObserver} object that receives callbacks when changes occur.
*/
@Override
public void registerContentObserver(@NonNull Uri uri, boolean notifyForDescendants, @NonNull ContentObserver observer) {
mContentResolver.registerContentObserver(uri, notifyForDescendants, observer);
}
/**
* Method that unregisters a registered change observer {@link ContentObserver}.
*
* @param observer The previously registered {@link ContentObserver} that is no longer needed.
*/
@Override
public void unregisterContentObserver(@NonNull ContentObserver observer) {
mContentResolver.unregisterContentObserver(observer);
}
/**
* Method that retrieves the Supplier Details of Supplier identified by its Id.
*
* @param supplierId The Integer Id of the Supplier to lookup for.
* @param queryCallback The Callback to be implemented by the caller to receive the result.
*/
@Override
public void getSupplierDetailsById(int supplierId, @NonNull GetQueryCallback<Supplier> queryCallback) {
//Retrieving the Supplier details for the Supplier ID passed
//Executing on Disk Thread
mAppExecutors.getDiskIO().execute(() -> {
//Retrieving the cursor to the record
Cursor cursor = mContentResolver.query(
ContentUris.withAppendedId(SupplierContract.Supplier.CONTENT_URI, supplierId),
QueryArgsUtility.SupplierByIdQuery.getProjection(),
null,
null,
null
);
//Retrieving the details from the Cursor
try {
if (cursor != null && cursor.moveToFirst()) {
//When the Cursor is NOT Null and there is a record for the Supplier being queried
//Retrieving the details of the Supplier
String name = cursor.getString(QueryArgsUtility.SupplierByIdQuery.COLUMN_SUPPLIER_NAME_INDEX);
String code = cursor.getString(QueryArgsUtility.SupplierByIdQuery.COLUMN_SUPPLIER_CODE_INDEX);
//Retrieving the Supplier's Contacts
ArrayList<SupplierContact> supplierContacts = getSupplierContacts(supplierId);
//Retrieving the Supplier's Items
ArrayList<ProductSupplierInfo> productSupplierInfoList = getProductSupplierInfoList(supplierId);
//Building the Supplier details
final Supplier supplier = new Supplier.Builder()
.setId(supplierId)
.setName(name)
.setCode(code)
.setContacts(supplierContacts)
.setProductSupplierInfoList(productSupplierInfoList)
.createSupplier();
//Executing on the Main Thread
mAppExecutors.getMainThread().execute(() -> {
//Pass the Supplier data to the callback
queryCallback.onResults(supplier);
});
} else {
//When Cursor is Null, the Supplier being queried is not found
//Pass the Supplier Not found error to the callback in this case.
queryCallback.onFailure(R.string.supplier_config_no_supplier_found_error, supplierId);
}