-
Notifications
You must be signed in to change notification settings - Fork 21
/
SupplierConfigActivityFragment.java
2265 lines (2007 loc) · 106 KB
/
SupplierConfigActivityFragment.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.ui.suppliers.config;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.recyclerview.extensions.ListAdapter;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.kaushiknsanji.storeapp.R;
import com.example.kaushiknsanji.storeapp.data.local.contracts.SupplierContract;
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.SupplierContact;
import com.example.kaushiknsanji.storeapp.ui.common.ProgressDialogFragment;
import com.example.kaushiknsanji.storeapp.ui.products.config.ProductConfigActivity;
import com.example.kaushiknsanji.storeapp.utils.ContactUtility;
import com.example.kaushiknsanji.storeapp.utils.OrientationUtility;
import com.example.kaushiknsanji.storeapp.utils.SnackbarUtility;
import com.example.kaushiknsanji.storeapp.workers.ImageDownloaderFragment;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
/**
* Content Fragment of {@link SupplierConfigActivity} that inflates the layout 'R.layout.fragment_supplier_config'
* to display/record the configuration details of the Supplier. This implements the
* {@link SupplierConfigContract.View} on the lines of Model-View-Presenter architecture.
*
* @author Kaushik N Sanji
*/
public class SupplierConfigActivityFragment extends Fragment
implements SupplierConfigContract.View, View.OnFocusChangeListener, View.OnClickListener {
//Constant used for logs
private static final String LOG_TAG = SupplierConfigActivityFragment.class.getSimpleName();
//The Bundle argument constant of this Fragment
private static final String ARGUMENT_INT_SUPPLIER_ID = "argument.SUPPLIER_ID";
//Bundle constants for persisting the data throughout System config changes
private static final String BUNDLE_SUPPLIER_CONTACTS_PHONE_KEY = "SupplierConfig.Contacts.Phone";
private static final String BUNDLE_SUPPLIER_CONTACTS_EMAIL_KEY = "SupplierConfig.Contacts.Email";
private static final String BUNDLE_SUPPLIER_PRODUCTS_DATA_SPARSE_ARRAY_KEY = "SupplierConfig.ProductLites";
private static final String BUNDLE_SUPPLIER_PRODUCTS_PRICE_KEY = "SupplierConfig.ProductSupplierInfos";
private static final String BUNDLE_EXISTING_SUPPLIER_RESTORED_BOOL_KEY = "SupplierConfig.IsExistingSupplierRestored";
private static final String BUNDLE_SUPPLIER_CODE_VALID_BOOL_KEY = "SupplierConfig.IsSupplierCodeValid";
private static final String BUNDLE_SUPPLIER_NAME_ENTERED_BOOL_KEY = "SupplierConfig.IsSupplierNameEntered";
//The Presenter for this View
private SupplierConfigContract.Presenter mPresenter;
//Stores the instance of the View components required
private EditText mEditTextSupplierName;
private TextInputLayout mTextInputSupplierCode;
private EditText mEditTextSupplierCode;
private RecyclerView mRecyclerViewContactPhone;
private RecyclerView mRecyclerViewContactEmail;
private RecyclerView mRecyclerViewSupplierProduct;
//The RecyclerView Adapter for Phone Contacts
private SupplierContactAdapter mPhoneContactsAdapter;
//The RecyclerView Adapter for Email Contacts
private SupplierContactAdapter mEmailContactsAdapter;
//The RecyclerView Adapter for Supplier Products
private SupplierProductsAdapter mSupplierProductsAdapter;
//Saves the Focus Change Listener registered view that had focus before save operation
private View mLastRegisteredFocusChangeView;
//Stores the Supplier ID for an Edit request, retrieved from the Bundle arguments passed
private int mSupplierId;
//Stores the state of Existing Supplier details restored,
//to prevent updating the fields every time during System config change
private boolean mIsExistingSupplierRestored;
//Stores whether the Supplier Code entered was valid or not
private boolean mIsSupplierCodeValid;
//Stores whether the Supplier Name was entered or not.
//Used for monitoring unsaved progress.
private boolean mIsSupplierNameEntered;
/**
* The {@link AlertDialog} Click Listener for the Supplier Delete Menu.
*/
private DialogInterface.OnClickListener mSupplierDeleteDialogOnClickListener = new DialogInterface.OnClickListener() {
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog the dialog that received the click
* @param which the button that was clicked (ex.
* {@link DialogInterface#BUTTON_POSITIVE}) or the position
*/
@Override
public void onClick(DialogInterface dialog, int which) {
//Taking action based on the button clicked
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//For "Yes" Button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
//Dispatch to the Presenter to delete the Supplier
mPresenter.deleteSupplier();
break;
case DialogInterface.BUTTON_NEGATIVE:
//For "No" Button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
break;
}
}
};
/**
* The {@link AlertDialog} Click Listener for the Unsaved changes dialog
*/
private DialogInterface.OnClickListener mUnsavedDialogOnClickListener = new DialogInterface.OnClickListener() {
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog the dialog that received the click
* @param which the button that was clicked (ex.
* {@link DialogInterface#BUTTON_POSITIVE}) or the position
*/
@Override
public void onClick(DialogInterface dialog, int which) {
//Taking action based on the button clicked
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//For "Save" button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
//Start saving the Supplier Entry
saveSupplier();
break;
case DialogInterface.BUTTON_NEGATIVE:
//For "Discard" button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
//Dispatch to the Presenter to finish the Activity
mPresenter.finishActivity();
break;
case DialogInterface.BUTTON_NEUTRAL:
//For "Keep Editing" button
//Just Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
break;
}
}
};
/**
* Mandatory Empty Constructor of {@link SupplierConfigActivityFragment}.
* This is required by the {@link android.support.v4.app.FragmentManager} to instantiate
* the fragment (e.g. upon screen orientation changes).
*/
public SupplierConfigActivityFragment() {
}
/**
* Static Factory Constructor that creates an instance of {@link SupplierConfigActivityFragment}
* using the provided {@code supplierId}
*
* @param supplierId The Integer value of the Supplier Id of an existing Supplier;
* or {@link SupplierConfigContract#NEW_SUPPLIER_INT} if it is
* for a New Supplier Entry.
* @return Instance of {@link SupplierConfigActivityFragment}
*/
public static SupplierConfigActivityFragment newInstance(int supplierId) {
//Saving the arguments passed, in a Bundle: START
Bundle args = new Bundle(1);
args.putInt(ARGUMENT_INT_SUPPLIER_ID, supplierId);
//Saving the arguments passed, in a Bundle: END
//Instantiating the Fragment
SupplierConfigActivityFragment fragment = new SupplierConfigActivityFragment();
//Passing the Bundle as Arguments to this Fragment
fragment.setArguments(args);
//Returning the fragment instance
return fragment;
}
/**
* Called to do initial creation of a fragment.
*
* @param savedInstanceState If the fragment is being re-created from
* a previous saved state, this is the state.
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Indicating that this fragment has menu options to show
setHasOptionsMenu(true);
}
/**
* Called to have the fragment instantiate its user interface view.
* This is optional, and non-graphical fragments can return null (which
* is the default implementation). This will be called between
* {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
* <p>
* <p>If you return a View from here, you will later be called in
* {@link #onDestroyView} when the view is being released.
*
* @param inflater The LayoutInflater object that can be used to inflate
* any views in the fragment,
* @param container If non-null, this is the parent view that the fragment's
* UI should be attached to. The fragment should not add the view itself,
* but this can be used to generate the LayoutParams of the view.
* @param savedInstanceState If non-null, this fragment is being re-constructed
* from a previous saved state as given here.
* @return Returns the View for the fragment's UI ('R.layout.fragment_supplier_config')
*/
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate the layout 'R.layout.fragment_supplier_config' for this fragment
//Passing false as we are attaching the layout ourselves
View rootView = inflater.inflate(R.layout.fragment_supplier_config, container, false);
//Finding the Views to initialize
mEditTextSupplierName = rootView.findViewById(R.id.edittext_supplier_config_name);
mTextInputSupplierCode = rootView.findViewById(R.id.textinput_supplier_config_code);
mEditTextSupplierCode = rootView.findViewById(R.id.edittext_supplier_config_code);
mRecyclerViewContactPhone = rootView.findViewById(R.id.recyclerview_supplier_config_phone);
mRecyclerViewContactEmail = rootView.findViewById(R.id.recyclerview_supplier_config_email);
mRecyclerViewSupplierProduct = rootView.findViewById(R.id.recyclerview_supplier_config_items);
//Registering the Focus Change Listener on the Supplier Name field
mEditTextSupplierName.setOnFocusChangeListener(this);
//Registering the Focus Change Listener on the Supplier Code field
mEditTextSupplierCode.setOnFocusChangeListener(this);
//Attaching a Text Watcher for the Supplier Code field
mEditTextSupplierCode.addTextChangedListener(new SupplierCodeTextWatcher());
//Registering Click Listener on "Add Phone" button
rootView.findViewById(R.id.btn_supplier_config_add_phone).setOnClickListener(this);
//Registering Click Listener on "Add Email" button
rootView.findViewById(R.id.btn_supplier_config_add_email).setOnClickListener(this);
//Registering Click Listener on "Add Item" button
rootView.findViewById(R.id.btn_supplier_config_add_item).setOnClickListener(this);
//Retrieving the Supplier Id from the Bundle
Bundle arguments = getArguments();
if (arguments != null) {
mSupplierId = arguments.getInt(ARGUMENT_INT_SUPPLIER_ID, SupplierConfigContract.NEW_SUPPLIER_INT);
}
//Initialize RecyclerView for Supplier Contact Phones
setupContactPhonesRecyclerView();
//Initialize RecyclerView for Supplier Contact Emails
setupContactEmailsRecyclerView();
//Initialize RecyclerView for Supplier Items
setupSupplierItemsRecyclerView();
//Returning the prepared layout
return rootView;
}
/**
* Method that registers the Presenter {@code presenter} with the View implementing
* {@link com.example.kaushiknsanji.storeapp.ui.BaseView}
*
* @param presenter Presenter instance implementing the {@link com.example.kaushiknsanji.storeapp.ui.BasePresenter}
*/
@Override
public void setPresenter(SupplierConfigContract.Presenter presenter) {
mPresenter = presenter;
}
/**
* Called when the fragment's activity has been created and this
* fragment's view hierarchy instantiated. It can be used to do final
* initialization once these pieces are in place, such as retrieving
* views or restoring state. It is also useful for fragments that use
* {@link #setRetainInstance(boolean)} to retain their instance,
* as this callback tells the fragment when it is fully associated with
* the new activity instance. This is called after {@link #onCreateView}
* and before {@link #onViewStateRestored(Bundle)}.
*
* @param savedInstanceState If the fragment is being re-created from
* a previous saved state, this is the state.
*/
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//On Subsequent launch
//Restoring Supplier Contacts
ArrayList<SupplierContact> phoneContactList = savedInstanceState.getParcelableArrayList(BUNDLE_SUPPLIER_CONTACTS_PHONE_KEY);
ArrayList<SupplierContact> emailContactList = savedInstanceState.getParcelableArrayList(BUNDLE_SUPPLIER_CONTACTS_EMAIL_KEY);
ArrayList<SupplierContact> supplierContacts = new ArrayList<>();
supplierContacts.addAll(phoneContactList);
supplierContacts.addAll(emailContactList);
mPresenter.updateSupplierContacts(supplierContacts);
//Restoring Supplier Items and Items data
SparseArray<ProductLite> productLiteSparseArray = savedInstanceState.getSparseParcelableArray(BUNDLE_SUPPLIER_PRODUCTS_DATA_SPARSE_ARRAY_KEY);
ArrayList<ProductSupplierInfo> productSupplierInfoList = savedInstanceState.getParcelableArrayList(BUNDLE_SUPPLIER_PRODUCTS_PRICE_KEY);
mPresenter.updateSupplierProducts(productSupplierInfoList, productLiteSparseArray);
//Restoring the state of Supplier Name Entered
mPresenter.updateAndSyncSupplierNameEnteredState(savedInstanceState.getBoolean(BUNDLE_SUPPLIER_NAME_ENTERED_BOOL_KEY, false));
//Restoring the state of Existing Supplier data being last restored
//if this was an Edit request
mPresenter.updateAndSyncExistingSupplierState(savedInstanceState.getBoolean(BUNDLE_EXISTING_SUPPLIER_RESTORED_BOOL_KEY, false));
//Restoring the state of Supplier Code Validation
mPresenter.updateAndSyncSupplierCodeValidity(savedInstanceState.getBoolean(BUNDLE_SUPPLIER_CODE_VALID_BOOL_KEY, false));
}
}
/**
* Called to ask the fragment to save its current dynamic state, so it
* can later be reconstructed in a new instance of its process is
* restarted. If a new instance of the fragment later needs to be
* created, the data you place in the Bundle here will be available
* in the Bundle given to {@link #onCreate(Bundle)},
* {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
* {@link #onActivityCreated(Bundle)}.
* <p>
* <p>This corresponds to {@link android.support.v4.app.FragmentActivity#onSaveInstanceState(Bundle)
* Activity.onSaveInstanceState(Bundle)} and most of the discussion there
* applies here as well.
*
* @param outState Bundle in which to place your saved state.
*/
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
//Trigger Focus Loss to capture any value partially entered
mPresenter.triggerFocusLost();
//Saving the state
outState.putParcelableArrayList(BUNDLE_SUPPLIER_CONTACTS_PHONE_KEY, mPhoneContactsAdapter.getSupplierContacts());
outState.putParcelableArrayList(BUNDLE_SUPPLIER_CONTACTS_EMAIL_KEY, mEmailContactsAdapter.getSupplierContacts());
outState.putSparseParcelableArray(BUNDLE_SUPPLIER_PRODUCTS_DATA_SPARSE_ARRAY_KEY, mSupplierProductsAdapter.getProductLiteSparseArray());
outState.putParcelableArrayList(BUNDLE_SUPPLIER_PRODUCTS_PRICE_KEY, mSupplierProductsAdapter.getProductSupplierInfoList());
outState.putBoolean(BUNDLE_EXISTING_SUPPLIER_RESTORED_BOOL_KEY, mIsExistingSupplierRestored);
outState.putBoolean(BUNDLE_SUPPLIER_CODE_VALID_BOOL_KEY, mIsSupplierCodeValid);
outState.putBoolean(BUNDLE_SUPPLIER_NAME_ENTERED_BOOL_KEY, mIsSupplierNameEntered);
}
/**
* Called when the fragment is visible to the user and actively running.
* This is generally
* tied to {@link android.support.v4.app.FragmentActivity#onResume() Activity.onResume} of the containing
* Activity's lifecycle.
*/
@Override
public void onResume() {
super.onResume();
//Start the work
mPresenter.start();
}
/**
* Initialize the contents of the Fragment host's standard options menu. You
* should place your menu items in to <var>menu</var>.
*
* @param menu The options menu in which you place your items.
* @param inflater The LayoutInflater object that can be used to inflate the Menu options
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Inflating the Menu options from 'R.menu.menu_fragment_supplier_config'
inflater.inflate(R.menu.menu_fragment_supplier_config, menu);
if (mSupplierId == SupplierConfigContract.NEW_SUPPLIER_INT) {
//For a New Supplier Entry, "Delete" Action Menu needs to be hidden and disabled
//Finding the Delete Action Menu Item
MenuItem deleteMenuItem = menu.findItem(R.id.action_delete);
//Hiding the Menu Item
deleteMenuItem.setVisible(false);
//Disabling the Menu Item
deleteMenuItem.setEnabled(false);
}
}
/**
* This hook is called whenever an item in your options menu is selected.
* The default implementation simply returns false to have the normal
* processing happen.
*
* @param item The menu item that was selected.
* @return boolean Return false to allow normal menu processing to
* proceed, true to consume it here.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handling based on the Menu item selected
switch (item.getItemId()) {
case R.id.action_delete:
//On Click of Delete Menu (applicable for an Existing Supplier entry only)
//Delegating to the Presenter to show the re-confirmation dialog
mPresenter.showDeleteSupplierDialog();
return true;
case R.id.action_save:
//On Click of Save Menu
//Saving the Supplier and its details
saveSupplier();
return true;
default:
//On other cases, do the default menu handling
return super.onOptionsItemSelected(item);
}
}
/**
* Method that grabs the data from the Views and dispatches to the Presenter
* to initiate the Save process.
*/
private void saveSupplier() {
//Delegating to the Presenter to trigger focus loss on listener registered View,
//in order to persist their data
mPresenter.triggerFocusLost();
//Retrieving the data from the views and the adapter
String supplierName = mEditTextSupplierName.getText().toString().trim();
String supplierCode = mEditTextSupplierCode.getText().toString().trim();
ArrayList<SupplierContact> phoneContacts = mPhoneContactsAdapter.getSupplierContacts();
ArrayList<SupplierContact> emailContacts = mEmailContactsAdapter.getSupplierContacts();
ArrayList<ProductSupplierInfo> productSupplierInfoList = mSupplierProductsAdapter.getProductSupplierInfoList();
//Delegating to the Presenter to initiate the Save process
mPresenter.onSave(supplierName,
supplierCode,
phoneContacts,
emailContacts,
productSupplierInfoList);
}
/**
* Called when the focus state of a view has changed.
*
* @param view The view whose state has changed.
* @param hasFocus The new focus state of {@code view}.
*/
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
//When a View has lost focus
//Clear the View reference since the View has lost focus
mLastRegisteredFocusChangeView = null;
//Taking action based on the Id of the View that has lost focus
switch (view.getId()) {
case R.id.edittext_supplier_config_name:
//For the EditText field of Supplier Name
//Update to the Presenter to notify that the Supplier Name has been entered
mPresenter.updateAndSyncSupplierNameEnteredState(!TextUtils.isEmpty(mEditTextSupplierName.getText().toString().trim()));
break;
case R.id.edittext_supplier_config_code:
//For the EditText field of Supplier Code
//Validate the Supplier Code entered, only for a New Supplier Entry
if (mSupplierId == SupplierConfigContract.NEW_SUPPLIER_INT) {
mPresenter.validateSupplierCode(mEditTextSupplierCode.getText().toString().trim());
}
break;
}
} else {
//When a View had gained focus
//Save the reference of the View in focus
mLastRegisteredFocusChangeView = view;
}
}
/**
* Called when a view has been clicked.
*
* @param view The view that was clicked.
*/
@Override
public void onClick(View view) {
//Executing based on the View Id
switch (view.getId()) {
case R.id.btn_supplier_config_add_phone:
//For "Add Phone" button, present under "Contact Details : Phone"
//Add an Empty row for capturing the Phone Contact Details
mPhoneContactsAdapter.addEmptyRecord();
break;
case R.id.btn_supplier_config_add_email:
//For "Add Email" button, present under "Contact Details : Email"
//Add an Empty row for capturing the Email Contact Details
mEmailContactsAdapter.addEmptyRecord();
break;
case R.id.btn_supplier_config_add_item:
//For "Add Item" button, present under "Supplier Items"
//Delegating to the Presenter to launch the Activity for picking Products
mPresenter.pickProducts(mSupplierProductsAdapter.getProductLiteList());
break;
}
}
/**
* Method that displays the Progress indicator
*
* @param statusTextId String resource for the status of the Progress to be shown.
*/
@Override
public void showProgressIndicator(@StringRes int statusTextId) {
ProgressDialogFragment.showDialog(getChildFragmentManager(), getString(statusTextId));
}
/**
* Method that hides the Progress indicator
*/
@Override
public void hideProgressIndicator() {
ProgressDialogFragment.dismissDialog(getChildFragmentManager());
}
/**
* Method invoked when an error is encountered during Supplier information
* retrieval or save process.
*
* @param messageId String Resource of the error Message to be displayed
* @param args Variable number of arguments to replace the format specifiers
* in the String resource if any
*/
@Override
public void showError(int messageId, @Nullable Object... args) {
if (getView() != null) {
//When we have the root view
//Evaluating the message to be shown
String messageToBeShown;
if (args != null && args.length > 0) {
//For the String Resource with args
messageToBeShown = getString(messageId, args);
} else {
//For the String Resource without args
messageToBeShown = getString(messageId);
}
if (!TextUtils.isEmpty(messageToBeShown)) {
//Displaying the Snackbar message of indefinite time length
//when we have the error message to be shown
new SnackbarUtility(Snackbar.make(getView(), messageToBeShown, Snackbar.LENGTH_INDEFINITE))
.revealCompleteMessage() //Removes the limit on max lines
.setDismissAction(R.string.snackbar_action_ok) //For the Dismiss "OK" action
.showSnack();
}
}
}
/**
* Method that locks the Supplier Code field to prevent updates on this field.
*/
@Override
public void lockSupplierCodeField() {
mTextInputSupplierCode.setEnabled(false);
}
/**
* Method invoked to keep the state of "Existing Supplier details restored", in sync with the Presenter.
*
* @param isExistingSupplierRestored Boolean that indicates the state of Existing Supplier data restored.
* <b>TRUE</b> if it had been restored; <b>FALSE</b> otherwise.
*/
@Override
public void syncExistingSupplierState(boolean isExistingSupplierRestored) {
//Saving the state
mIsExistingSupplierRestored = isExistingSupplierRestored;
}
/**
* Method invoked to keep the state of "Supplier Code Validity", in sync with the Presenter.
*
* @param isSupplierCodeValid Boolean that indicates whether the Supplier Code entered was valid or not.
* <b>TRUE</b> if the Supplier Code is valid; <b>FALSE</b> otherwise.
*/
@Override
public void syncSupplierCodeValidity(boolean isSupplierCodeValid) {
//Saving the state
mIsSupplierCodeValid = isSupplierCodeValid;
}
/**
* Method invoked to keep the state of "Supplier Name entered", in sync with the Presenter.
* This is used for monitoring unsaved progress.
*
* @param isSupplierNameEntered Boolean that indicates whether the Supplier Name has been entered by the User or not.
* <b>TRUE</b> if the Supplier Name is entered; <b>FALSE</b> otherwise.
*/
@Override
public void syncSupplierNameEnteredState(boolean isSupplierNameEntered) {
//Saving the state
mIsSupplierNameEntered = isSupplierNameEntered;
}
/**
* Method invoked when the Supplier Code entered by the user is NOT Unique
* causing the conflict.
*/
@Override
public void showSupplierCodeConflictError() {
//Request the user to try a different Supplier Code
//Show error on the EditText
mTextInputSupplierCode.setError(getString(R.string.supplier_config_code_invalid_error));
}
/**
* Method that updates the Supplier Name {@code supplierName} to the View
*
* @param supplierName The Name of the Supplier
*/
@Override
public void updateSupplierNameField(String supplierName) {
mEditTextSupplierName.setText(supplierName);
}
/**
* Method that updates the Supplier Code {@code supplierCode} to the View
*
* @param supplierCode The Code of the Supplier
*/
@Override
public void updateSupplierCodeField(String supplierCode) {
mEditTextSupplierCode.setText(supplierCode);
}
/**
* Method that updates the Supplier's Phone Contacts {@code phoneContacts} to the View
*
* @param phoneContacts List of {@link SupplierContact} of Phone Contact Type, of the Supplier
*/
@Override
public void updatePhoneContacts(ArrayList<SupplierContact> phoneContacts) {
//Updating the data of the Supplier Contacts Adapter for Phone
mPhoneContactsAdapter.replaceSupplierContactList(phoneContacts);
}
/**
* Method that updates the Supplier's Email Contacts {@code emailContacts} to the View
*
* @param emailContacts List of {@link SupplierContact} of Email Contact Type, of the Supplier
*/
@Override
public void updateEmailContacts(ArrayList<SupplierContact> emailContacts) {
//Updating the data of the Supplier Contacts Adapter for Email
mEmailContactsAdapter.replaceSupplierContactList(emailContacts);
}
/**
* Method that updates the List of Products {@link ProductLite} sold
* by the Supplier with Price information {@link ProductSupplierInfo}, to the View.
*
* @param productSupplierInfoList The List of {@link ProductSupplierInfo} which contains the
* Products with Price details that is sold by the Supplier.
* @param productLiteSparseArray {@link SparseArray} of {@link ProductLite} which contains the
* data of the Products sold by the Supplier.
*/
@Override
public void updateSupplierProducts(ArrayList<ProductSupplierInfo> productSupplierInfoList,
@Nullable SparseArray<ProductLite> productLiteSparseArray) {
//Submitting to the Adapter
mSupplierProductsAdapter.submitData(productSupplierInfoList, productLiteSparseArray);
}
/**
* Method invoked when No Supplier Code was entered by the user.
*/
@Override
public void showSupplierCodeEmptyError() {
//Show error on the EditText
mTextInputSupplierCode.setError(getString(R.string.supplier_config_code_empty_error));
}
/**
* Method invoked before save operation or screen orientation change to persist
* any data held by the view that had focus and its listener registered.
* This clears the focus held by the view to trigger the listener, causing to persist any unsaved data.
*/
@Override
public void triggerFocusLost() {
//Clearing focus on the last registered view
if (mLastRegisteredFocusChangeView != null) {
mLastRegisteredFocusChangeView.clearFocus();
mLastRegisteredFocusChangeView = null;
}
//Clearing focus on the last registered view in Phone Contacts Adapter
if (mPhoneContactsAdapter != null) {
mPhoneContactsAdapter.triggerFocusLost();
}
//Clearing focus on the last registered view in Email Contacts Adapter
if (mEmailContactsAdapter != null) {
mEmailContactsAdapter.triggerFocusLost();
}
//Clearing focus on the last registered view in Supplier Products Adapter
if (mSupplierProductsAdapter != null) {
mSupplierProductsAdapter.triggerFocusLost();
}
}
/**
* Method invoked when required fields are missing data, on click of 'Save' Menu button.
*/
@Override
public void showEmptyFieldsValidationError() {
showError(R.string.supplier_config_empty_fields_validation_error);
}
/**
* Method invoked when more than one {@link SupplierContact} is found to have
* the same Contact value {@code contactValue}.
*
* @param conflictMessageResId The String resource of conflict error message to be shown.
* @param contactValue The Contact Value which is repeated causing the conflict.
*/
@Override
public void showSupplierContactConflictError(@StringRes int conflictMessageResId, String contactValue) {
showError(conflictMessageResId, contactValue);
}
/**
* Method invoked when there is no contact information configured for the Supplier.
*/
@Override
public void showEmptyContactsError() {
showError(R.string.supplier_config_empty_contacts_error);
}
/**
* Method invoked by the Presenter to display the Discard dialog,
* requesting the User whether to keep editing/discard the changes
*/
@Override
public void showDiscardDialog() {
//Creating an AlertDialog with a message, and listeners for the positive, neutral and negative buttons
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
//Set the Message
builder.setMessage(R.string.supplier_config_unsaved_changes_dialog_message);
//Set the Positive Button and its listener
builder.setPositiveButton(R.string.supplier_config_unsaved_changes_dialog_positive_text, mUnsavedDialogOnClickListener);
//Set the Negative Button and its listener
builder.setNegativeButton(R.string.supplier_config_unsaved_changes_dialog_negative_text, mUnsavedDialogOnClickListener);
//Set the Neutral Button and its listener
builder.setNeutralButton(R.string.supplier_config_unsaved_changes_dialog_neutral_text, mUnsavedDialogOnClickListener);
//Lock the Orientation
OrientationUtility.lockCurrentScreenOrientation(requireActivity());
//Create and display the AlertDialog
builder.create().show();
}
/**
* Method invoked when the user clicks on the Delete Menu Action to delete the Supplier.
* This should launch a Dialog for the user to reconfirm the request before proceeding
* with the Delete Action.
*/
@Override
public void showDeleteSupplierDialog() {
//Creating an AlertDialog with a message, and listeners for the positive and negative buttons
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
//Set the Message
builder.setMessage(R.string.supplier_config_delete_supplier_confirm_dialog_message);
//Set the Positive Button and its listener
builder.setPositiveButton(android.R.string.yes, mSupplierDeleteDialogOnClickListener);
//Set the Negative Button and its listener
builder.setNegativeButton(android.R.string.no, mSupplierDeleteDialogOnClickListener);
//Lock the Orientation
OrientationUtility.lockCurrentScreenOrientation(requireActivity());
//Create and display the AlertDialog
builder.create().show();
}
/**
* Method invoked when the user swipes left/right any Item View of the Products sold by the Supplier
* in order to remove it from the list. This should show a Snackbar with Action UNDO.
*
* @param productSku The Product SKU of the Product being swiped out.
*/
@Override
public void showSupplierProductSwiped(String productSku) {
if (getView() != null) {
new SnackbarUtility(Snackbar.make(getView(),
getString(R.string.supplier_config_product_swipe_action_success,
productSku), Snackbar.LENGTH_LONG))
.revealCompleteMessage()
.setAction(R.string.snackbar_action_undo, (view) -> {
//Try and Restore the Adapter data when UNDO is clicked
if (mSupplierProductsAdapter.restoreLastRemovedProduct()) {
//On Success, show a Snackbar message
Snackbar.make(getView(),
getString(R.string.supplier_config_product_swipe_action_undo_success, productSku),
Snackbar.LENGTH_LONG).show();
}
})
.showSnack();
}
}
/**
* Method that displays a message on Success of Updating an Existing Product.
*
* @param productSku String containing the SKU of the Product that was updated successfully.
*/
@Override
public void showUpdateSuccess(String productSku) {
if (getView() != null) {
Snackbar.make(getView(), getString(R.string.product_list_item_update_success, productSku), Snackbar.LENGTH_LONG).show();
}
}
/**
* Method that displays a message on Success of Deleting an Existing Product
*
* @param productSku String containing the SKU of the Product that was deleted successfully.
*/
@Override
public void showDeleteSuccess(String productSku) {
if (getView() != null) {
Snackbar.make(getView(), getString(R.string.product_list_item_delete_success, productSku), Snackbar.LENGTH_LONG).show();
}
}
/**
* Method invoked when one of the Supplier's Products were edited successfully and
* returned through Activity result. This method should notify the Adapter to rebind
* the data for the product with Id {@code productId}
*
* @param productId The Integer Id of the Product whose data needs to be rebound.
*/
@Override
public void notifyProductChanged(int productId) {
//Delegating to the Adapter to rebind
mSupplierProductsAdapter.notifyProductChanged(productId);
}
/**
* Method invoked during save operation, when a {@link SupplierContact}
* value is found to be still invalid.
*
* @param invalidMessageResId The String resource of the error message to be shown.
*/
@Override
public void showSupplierContactsInvalidError(@StringRes int invalidMessageResId) {
showError(invalidMessageResId);
}
/**
* Method that initializes the RecyclerView 'R.id.recyclerview_supplier_config_phone' and its Adapter.
*/
private void setupContactPhonesRecyclerView() {
//Creating a Vertical Linear Layout Manager with default layout order
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireContext(),
LinearLayoutManager.VERTICAL, false);
//Setting the Layout Manager to use
mRecyclerViewContactPhone.setLayoutManager(linearLayoutManager);
//Initializing the Adapter
mPhoneContactsAdapter = new SupplierContactAdapter(SupplierContract.SupplierContactType.CONTACT_TYPE_PHONE);
//Setting the Adapter on RecyclerView
mRecyclerViewContactPhone.setAdapter(mPhoneContactsAdapter);
}
/**
* Method that initializes the RecyclerView 'R.id.recyclerview_supplier_config_email' and its Adapter.
*/
private void setupContactEmailsRecyclerView() {
//Creating a Vertical Linear Layout Manager with default layout order
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireContext(),
LinearLayoutManager.VERTICAL, false);
//Setting the Layout Manager to use
mRecyclerViewContactEmail.setLayoutManager(linearLayoutManager);
//Initializing the Adapter
mEmailContactsAdapter = new SupplierContactAdapter(SupplierContract.SupplierContactType.CONTACT_TYPE_EMAIL);
//Setting the Adapter on RecyclerView
mRecyclerViewContactEmail.setAdapter(mEmailContactsAdapter);
}
/**
* Method that initializes the RecyclerView 'R.id.recyclerview_supplier_config_items' and its Adapter.
*/
private void setupSupplierItemsRecyclerView() {
//Creating a Vertical Linear Layout Manager with default layout order
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireContext(),
LinearLayoutManager.VERTICAL, false);
//Setting the Layout Manager to use
mRecyclerViewSupplierProduct.setLayoutManager(linearLayoutManager);
//Initializing the Adapter
mSupplierProductsAdapter = new SupplierProductsAdapter(requireContext(), new SupplierProductItemUserActionsListener());
//Setting the Adapter on RecyclerView
mRecyclerViewSupplierProduct.setAdapter(mSupplierProductsAdapter);
//Attaching the ItemTouchHelper for Swipe delete
mSupplierProductsAdapter.getItemTouchHelper().attachToRecyclerView(mRecyclerViewSupplierProduct);
}
/**
* RecyclerView {@link android.support.v7.widget.RecyclerView.Adapter} class to load the
* list of {@link SupplierContact} to be displayed
*/
private static class SupplierContactAdapter extends RecyclerView.Adapter<SupplierContactAdapter.ViewHolder> {
//Payload constants used to rebind the state of list items for the position stored here
private static final String PAYLOAD_NEW_DEFAULT_CONTACT = "Payload.NewDefaultContactPosition";