aboutsummaryrefslogtreecommitdiff
path: root/java/src/com/android/i18n/addressinput/AddressWidget.java
blob: 8a598ffaf9e5cab243f9d403202ad428801a6441 (plain)
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
/*
 * Copyright (C) 2010 Google Inc.
 *
 * 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 com.android.i18n.addressinput;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.i18n.addressinput.AddressField.WidthType;
import com.android.i18n.addressinput.AddressUiComponent.UiComponent;
import com.android.i18n.addressinput.LookupKey.KeyType;
import com.android.i18n.addressinput.LookupKey.ScriptType;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Address widget that lays out address fields, validate and format addresses according to local
 * customs.
 */
public class AddressWidget implements AdapterView.OnItemSelectedListener {
    private Context mContext;

    private ViewGroup mRootView;

    private LayoutInflater mInflater;

    private CacheData mCacheData;

    // A map for all address fields.
    private final EnumMap<AddressField, AddressUiComponent> mInputWidgets =
        new EnumMap<AddressField, AddressUiComponent>(AddressField.class);

    private FormController mFormController;

    private FormatInterpreter mFormatInterpreter;

    private FormOptions mFormOptions;

    private StandardAddressVerifier mVerifier;

    private ProgressDialog mProgressDialog;

    private String mCurrentRegion;

    // The current language the widget uses in BCP47 format. It differs from the default locale of
    // the phone in that it contains information on the script to use.
    private String mWidgetLocale;

    private ScriptType mScript;

    // Possible labels that could be applied to the admin area field of the current country.
    // Examples include "state", "province", "emirate", etc.
    private static final Map<String, Integer> ADMIN_LABELS;
    // Possible labels that could be applied to the locality (city) field of the current country.
    // Examples include "city" or "district".
    private static final Map<String, Integer> LOCALITY_LABELS;
    // Possible labels that could be applied to the sublocality field of the current country.
    // Examples include "suburb" or "neighborhood".
    private static final Map<String, Integer> SUBLOCALITY_LABELS;

    private static final FormOptions SHOW_ALL_FIELDS = new FormOptions.Builder().build();

    // The appropriate label that should be applied to the zip code field of the current country.
    private enum ZipLabel {
        ZIP,
        POSTAL
    }

    private ZipLabel mZipLabel;

    static {
        Map<String, Integer> adminLabelMap = new HashMap<String, Integer>(15);
        adminLabelMap.put("area", R.string.i18n_area);
        adminLabelMap.put("county", R.string.i18n_county);
        adminLabelMap.put("department", R.string.i18n_department);
        adminLabelMap.put("district", R.string.i18n_district);
        adminLabelMap.put("do_si", R.string.i18n_do_si);
        adminLabelMap.put("emirate", R.string.i18n_emirate);
        adminLabelMap.put("island", R.string.i18n_island);
        adminLabelMap.put("oblast", R.string.i18n_oblast);
        adminLabelMap.put("parish", R.string.i18n_parish);
        adminLabelMap.put("prefecture", R.string.i18n_prefecture);
        adminLabelMap.put("province", R.string.i18n_province);
        adminLabelMap.put("state", R.string.i18n_state);
        ADMIN_LABELS = Collections.unmodifiableMap(adminLabelMap);

        Map<String, Integer> localityLabelMap = new HashMap<String, Integer>(2);
        localityLabelMap.put("city", R.string.i18n_locality_label);
        localityLabelMap.put("district", R.string.i18n_district);
        localityLabelMap.put("post_town", R.string.i18n_post_town);
        LOCALITY_LABELS = Collections.unmodifiableMap(localityLabelMap);

        Map<String, Integer> sublocalityLabelMap = new HashMap<String, Integer>(2);
        sublocalityLabelMap.put("suburb", R.string.i18n_suburb);
        sublocalityLabelMap.put("district", R.string.i18n_district);
        sublocalityLabelMap.put("neighborhood", R.string.i18n_neighborhood);
        sublocalityLabelMap.put("village_township", R.string.i18n_village_township);
        SUBLOCALITY_LABELS = Collections.unmodifiableMap(sublocalityLabelMap);
    }

    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    final Runnable mUpdateMultipleFields = new Runnable() {
        @Override
        public void run() {
            updateFields();
        }
    };

    private class UpdateRunnable implements Runnable {
        private AddressField myId;

        public UpdateRunnable(AddressField id) {
            myId = id;
        }

        @Override
        public void run() {
            updateInputWidget(myId);
        }
    }

    private static class AddressSpinnerInfo {
        private Spinner mView;

        private AddressField mId;

        private AddressField mParentId;

        private ArrayAdapter<String> mAdapter;

        private List<RegionData> mCurrentRegions;

        @SuppressWarnings("unchecked")
        public AddressSpinnerInfo(Spinner view, AddressField id, AddressField parentId) {
            mView = view;
            mId = id;
            mParentId = parentId;
            mAdapter = (ArrayAdapter<String>) view.getAdapter();
        }

        public void setSpinnerList(List<RegionData> list, String defaultKey) {
            mCurrentRegions = list;
            mAdapter.clear();
            for (RegionData item : list) {
                mAdapter.add(item.getDisplayName());
            }
            mAdapter.sort(Collator.getInstance(Locale.getDefault()));
            if (defaultKey.length() == 0) {
                mView.setSelection(0);
            } else {
                int position = mAdapter.getPosition(defaultKey);
                mView.setSelection(position);
            }
        }

        // Returns the region key of the currently selected region in the Spinner.
        public String getRegionCode(int position) {
            if (mAdapter.getCount() <= position) {
                return "";
            }
            String value = mAdapter.getItem(position);
            return getRegionDataKeyForValue(value);
        }

        // Returns the region key for the region value.
        public String getRegionDataKeyForValue(String value) {
            for (RegionData data : mCurrentRegions) {
                if (data.getDisplayName().endsWith(value)) {
                    return data.getKey();
                }
            }
            return "";
        }
    }

    private final ArrayList<AddressSpinnerInfo> mSpinners = new ArrayList<AddressSpinnerInfo>();

    private AddressWidgetUiComponentProvider mComponentProvider;

    /** TODO: Add region-dependent width types for address fields. */
    private WidthType getFieldWidthType(AddressUiComponent field) {
        return field.getId().getDefaulWidthType();
    }

    private void createView(ViewGroup rootView, AddressUiComponent field, String defaultKey,
            boolean readOnly) {
        @SuppressWarnings("deprecation")  // FILL_PARENT renamed MATCH_PARENT in API Level 8.
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        String fieldText = field.getFieldName();
        WidthType widthType = getFieldWidthType(field);

        if (fieldText.length() > 0) {
            TextView textView = mComponentProvider.createUiLabel(fieldText, widthType);
            rootView.addView(textView, lp);
        }
        if (field.getUiType().equals(UiComponent.EDIT)) {
            EditText editText = mComponentProvider.createUiTextField(widthType);
            field.setView(editText);
            editText.setEnabled(!readOnly);
            rootView.addView(editText, lp);
        } else if (field.getUiType().equals(UiComponent.SPINNER)) {
            ArrayAdapter<String> adapter = mComponentProvider.createUiPickerAdapter(widthType);
            Spinner spinner = mComponentProvider.createUiPickerSpinner(widthType);

            field.setView(spinner);
            rootView.addView(spinner, lp);
            spinner.setAdapter(adapter);
            AddressSpinnerInfo spinnerInfo =
                    new AddressSpinnerInfo(spinner, field.getId(), field.getParentId());
            spinnerInfo.setSpinnerList(field.getCandidatesList(), defaultKey);

            if (fieldText.length() > 0) {
                spinner.setPrompt(fieldText);
            }
            spinner.setOnItemSelectedListener(this);
            mSpinners.add(spinnerInfo);
        }
    }

    /**
     *  Associates each field with its corresponding AddressUiComponent.
     */
    private void buildFieldWidgets() {
        AddressData data = new AddressData.Builder().setCountry(mCurrentRegion).build();
        LookupKey key = new LookupKey.Builder(LookupKey.KeyType.DATA).setAddressData(data).build();
        AddressVerificationNodeData countryNode =
            (new ClientData(mCacheData)).getDefaultData(key.toString());

        // Set up AddressField.ADMIN_AREA
        AddressUiComponent adminAreaUi = new AddressUiComponent(AddressField.ADMIN_AREA);
        adminAreaUi.setFieldName(getAdminAreaFieldName(countryNode));
        mInputWidgets.put(AddressField.ADMIN_AREA, adminAreaUi);

        // Set up AddressField.LOCALITY
        AddressUiComponent localityUi = new AddressUiComponent(AddressField.LOCALITY);
        localityUi.setFieldName(getLocalityFieldName(countryNode));
        mInputWidgets.put(AddressField.LOCALITY, localityUi);

        // Set up AddressField.DEPENDENT_LOCALITY
        AddressUiComponent subLocalityUi = new AddressUiComponent(AddressField.DEPENDENT_LOCALITY);
        subLocalityUi.setFieldName(getSublocalityFieldName(countryNode));
        mInputWidgets.put(AddressField.DEPENDENT_LOCALITY, subLocalityUi);

        // Set up AddressField.ADDRESS_LINE_1
        AddressUiComponent addressLine1Ui = new AddressUiComponent(AddressField.ADDRESS_LINE_1);
        addressLine1Ui.setFieldName(mContext.getString(R.string.i18n_address_line1_label));
        mInputWidgets.put(AddressField.ADDRESS_LINE_1, addressLine1Ui);

        // Set up AddressField.ADDRESS_LINE_2
        AddressUiComponent addressLine2Ui = new AddressUiComponent(AddressField.ADDRESS_LINE_2);
        addressLine2Ui.setFieldName("");
        mInputWidgets.put(AddressField.ADDRESS_LINE_2, addressLine2Ui);

        // Set up AddressField.ORGANIZATION
        AddressUiComponent organizationUi = new AddressUiComponent(AddressField.ORGANIZATION);
        organizationUi.setFieldName(mContext.getString(R.string.i18n_organization_label));
        mInputWidgets.put(AddressField.ORGANIZATION, organizationUi);

        // Set up AddressField.RECIPIENT
        AddressUiComponent recipientUi = new AddressUiComponent(AddressField.RECIPIENT);
        recipientUi.setFieldName(mContext.getString(R.string.i18n_recipient_label));
        mInputWidgets.put(AddressField.RECIPIENT, recipientUi);

        // Set up AddressField.POSTAL_CODE
        AddressUiComponent postalCodeUi = new AddressUiComponent(AddressField.POSTAL_CODE);
        postalCodeUi.setFieldName(getZipFieldName(countryNode));
        mInputWidgets.put(AddressField.POSTAL_CODE, postalCodeUi);

        // Set up AddressField.SORTING_CODE
        AddressUiComponent sortingCodeUi = new AddressUiComponent(AddressField.SORTING_CODE);
        sortingCodeUi.setFieldName("CEDEX");
        mInputWidgets.put(AddressField.SORTING_CODE, sortingCodeUi);
    }

    private void initializeDropDowns() {
        AddressUiComponent adminAreaUi = mInputWidgets.get(AddressField.ADMIN_AREA);
        List<RegionData> adminAreaList = getRegionData(AddressField.COUNTRY);
        adminAreaUi.initializeCandidatesList(adminAreaList);

        AddressUiComponent localityUi = mInputWidgets.get(AddressField.LOCALITY);
        List<RegionData> localityList = getRegionData(AddressField.ADMIN_AREA);
        localityUi.initializeCandidatesList(localityList);
    }

    // ZIP code is called postal code in some countries. This method returns the appropriate name
    // for the given countryNode.
    private String getZipFieldName(AddressVerificationNodeData countryNode) {
        String zipName;
        String zipType = countryNode.get(AddressDataKey.ZIP_NAME_TYPE);
        if (zipType == null) {
            mZipLabel = ZipLabel.POSTAL;
            zipName = mContext.getString(R.string.i18n_postal_code_label);
        } else {
            mZipLabel = ZipLabel.ZIP;
            zipName = mContext.getString(R.string.i18n_zip_code_label);
        }
        return zipName;
    }

    private String getLocalityFieldName(AddressVerificationNodeData countryNode) {
        String localityLabelType = countryNode.get(AddressDataKey.LOCALITY_NAME_TYPE);
        Integer result = LOCALITY_LABELS.get(localityLabelType);
        if (result == null) {
            // Fallback to city.
            result = R.string.i18n_locality_label;
        }
        return mContext.getString(result);
    }

    private String getSublocalityFieldName(AddressVerificationNodeData countryNode) {
        String sublocalityLabelType = countryNode.get(AddressDataKey.SUBLOCALITY_NAME_TYPE);
        Integer result = SUBLOCALITY_LABELS.get(sublocalityLabelType);
        if (result == null) {
            // Fallback to suburb.
            result = R.string.i18n_suburb;
        }
        return mContext.getString(result);
    }

    private String getAdminAreaFieldName(AddressVerificationNodeData countryNode) {
        String adminLabelType = countryNode.get(AddressDataKey.STATE_NAME_TYPE);
        Integer result = ADMIN_LABELS.get(adminLabelType);
        if (result == null) {
            // Fallback to province.
            result = R.string.i18n_province;
        }
        return mContext.getString(result);
    }

    private void buildCountryListBox() {
        // Set up AddressField.COUNTRY
        AddressUiComponent countryUi = new AddressUiComponent(AddressField.COUNTRY);
        countryUi.setFieldName(mContext.getString(R.string.i18n_country_or_region_label));
        ArrayList<RegionData> countries = new ArrayList<RegionData>();
        for (RegionData regionData : mFormController.getRegionData(new LookupKey.Builder(
                KeyType.DATA).build())) {
            String regionKey = regionData.getKey();
            // ZZ represents an unknown region code.
            if (!regionKey.equals("ZZ")) {
                String localCountryName = getLocalCountryName(regionKey);
                RegionData country = new RegionData.Builder().setKey(regionKey).setName(
                        localCountryName).build();
                countries.add(country);
            }
        }
        countryUi.initializeCandidatesList(countries);
        mInputWidgets.put(AddressField.COUNTRY, countryUi);
    }

    private String getLocalCountryName(String regionCode) {
        return (new Locale("", regionCode)).getDisplayCountry(Locale.getDefault());
    }

    private AddressSpinnerInfo findSpinnerByView(View view) {
        for (AddressSpinnerInfo spinnerInfo : mSpinners) {
            if (spinnerInfo.mView == view) {
                return spinnerInfo;
            }
        }
        return null;
    }

    private void updateFields() {
        removePreviousViews();
        buildFieldWidgets();
        initializeDropDowns();
        layoutAddressFields();
    }

    private void removePreviousViews() {
        if (mRootView == null) {
            return;
        }
        int childCount = mRootView.getChildCount();
        if (mFormOptions.isHidden(AddressField.COUNTRY)) {
            if (childCount > 0) {
                mRootView.removeAllViews();
            }
        } else if (childCount > 2) {
            // Keep the TextView and Spinner for Country and remove everything else.
            mRootView.removeViews(2, mRootView.getChildCount() - 2);
        }
    }

    private void layoutAddressFields() {
        for (AddressField field : mFormatInterpreter.getAddressFieldOrder(mScript,
                mCurrentRegion)) {
            if (!mFormOptions.isHidden(field)) {
              createView(mRootView, mInputWidgets.get(field), "", mFormOptions.isReadonly(field));
            }
        }
    }

    private void updateChildNodes(AdapterView<?> parent, int position) {
        AddressSpinnerInfo spinnerInfo = findSpinnerByView(parent);
        if (spinnerInfo == null) {
            return;
        }

        // Find all the child spinners, if any, that depend on this one.
        final AddressField myId = spinnerInfo.mId;
        if (myId != AddressField.COUNTRY && myId != AddressField.ADMIN_AREA
                && myId != AddressField.LOCALITY) {
            // Only a change in the three AddressFields above will trigger a change in other
            // AddressFields. Therefore, for all other AddressFields, we return immediately.
            return;
        }

        String regionCode = spinnerInfo.getRegionCode(position);
        if (myId == AddressField.COUNTRY) {
            updateWidgetOnCountryChange(regionCode);
            return;
        }

        mFormController.requestDataForAddress(getAddressData(), new DataLoadListener() {
            @Override
            public void dataLoadingBegin(){
            }

            @Override
            public void dataLoadingEnd() {
                Runnable updateChild = new UpdateRunnable(myId);
                mHandler.post(updateChild);
            }
        });
    }

    public void updateWidgetOnCountryChange(String regionCode) {
        if (mCurrentRegion.equalsIgnoreCase(regionCode)) {
            return;
        }
        mCurrentRegion = regionCode;
        mFormController.setCurrentCountry(mCurrentRegion);
        renderForm();
    }

    private void updateInputWidget(AddressField myId) {
        for (AddressSpinnerInfo child : mSpinners) {
            if (child.mParentId == myId) {
                List<RegionData> candidates = getRegionData(child.mParentId);
                child.setSpinnerList(candidates, "");
            }
        }
    }

    public void renderForm() {
        setWidgetLocaleAndScript();
        AddressData data = new AddressData.Builder().setCountry(mCurrentRegion)
                .setLanguageCode(mWidgetLocale).build();
        mFormController.requestDataForAddress(data, new DataLoadListener() {
            @Override
            public void dataLoadingBegin() {
                mProgressDialog = mComponentProvider.getUiActivityIndicatorView();
                mProgressDialog.setMessage(mContext.getString(R.string.address_data_loading));
                Log.d(this.toString(), "Progress dialog started.");
            }
            @Override
            public void dataLoadingEnd() {
                Log.d(this.toString(), "Data loading completed.");
                mProgressDialog.dismiss();
                Log.d(this.toString(), "Progress dialog stopped.");
                mHandler.post(mUpdateMultipleFields);
            }
        });
    }

    private void setWidgetLocaleAndScript() {
        mWidgetLocale = Util.getWidgetCompatibleLanguageCode(Locale.getDefault(), mCurrentRegion);
        mFormController.setLanguageCode(mWidgetLocale);
        mScript = Util.isExplicitLatinScript(mWidgetLocale)
                ? ScriptType.LATIN
                : ScriptType.LOCAL;
    }

    private List<RegionData> getRegionData(AddressField parentField) {
        AddressData address = getAddressData();

        // Removes language code from address if it is default. This address is used to build
        // lookup key, which neglects default language. For example, instead of "data/US--en/CA",
        // the right lookup key is "data/US/CA".
        if (mFormController.isDefaultLanguage(address.getLanguageCode())) {
            address = new AddressData.Builder(address).setLanguageCode(null).build();
        }

        LookupKey parentKey = mFormController.getDataKeyFor(address).getKeyForUpperLevelField(
                parentField);
        List<RegionData> candidates;
        // Can't build a key with parent field, quit.
        if (parentKey == null) {
            Log.w(this.toString(), "Can't build key with parent field " + parentField + ". One of"
                    + " the ancestor fields might be empty");

            // Removes candidates that exist from previous settings. For example, data/US has a
            // list of candidates AB, BC, CA, etc, that list should be cleaned up when user updates
            // the address by changing country to Channel Islands.
            candidates = new ArrayList<RegionData>(1);
        } else {
            candidates = mFormController.getRegionData(parentKey);
        }
        return candidates;
    }

    /**
     * Creates an AddressWidget to be attached to rootView for the specific context using the
     * default UI component provider.
     */
    public AddressWidget(Context context, ViewGroup rootView, FormOptions formOptions,
            ClientCacheManager cacheManager) {
        this(context, rootView, formOptions, cacheManager,
                new AddressWidgetUiComponentProvider(context));
    }

    /**
     * Creates an AddressWidget to be attached to rootView for the specific context using UI
     * component provided by the provider.
     */
    public AddressWidget(Context context, ViewGroup rootView, FormOptions formOptions,
            ClientCacheManager cacheManager, AddressWidgetUiComponentProvider provider) {
        mComponentProvider = provider;
        mCurrentRegion =
            ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getSimCountryIso().toUpperCase(Locale.US);
        if (mCurrentRegion.length() == 0) {
            mCurrentRegion = "US";
        }
        init(context, rootView, formOptions, cacheManager);
        renderForm();
    }

    /**
     * Creates an AddressWidget to be attached to rootView for the specific context using the
     * default UI component provider, and fill out the address form with savedAddress.
     */
    public AddressWidget(Context context, ViewGroup rootView, FormOptions formOptions,
            ClientCacheManager cacheManager, AddressData savedAddress) {
        this(context, rootView, formOptions, cacheManager, savedAddress,
                new AddressWidgetUiComponentProvider(context));
    }

    /**
     * Creates an AddressWidget to be attached to rootView for the specific context using UI
     * component provided by the provider, and fill out the address form with savedAddress.
     */
    public AddressWidget(Context context, ViewGroup rootView, FormOptions formOptions,
            ClientCacheManager cacheManager, AddressData savedAddress,
            AddressWidgetUiComponentProvider provider) {
        mComponentProvider = provider;
        mCurrentRegion = savedAddress.getPostalCountry();
        // Postal country must be 2 letter country code. Otherwise default to US.
        if (mCurrentRegion == null || mCurrentRegion.length() != 2) {
            mCurrentRegion = "US";
        }
        init(context, rootView, formOptions, cacheManager);
        renderFormWithSavedAddress(savedAddress);
    }

    public void renderFormWithSavedAddress(AddressData savedAddress) {
        setWidgetLocaleAndScript();
        removePreviousViews();
        buildFieldWidgets();
        layoutAddressFields();
        initializeFieldsWithAddress(savedAddress);
    }

    private void initializeFieldsWithAddress(AddressData savedAddress) {
        for (AddressField field : mFormatInterpreter.getAddressFieldOrder(mScript,
                mCurrentRegion)) {
            String value = savedAddress.getFieldValue(field);
            if (value == null) {
                value = "";
            }
            AddressUiComponent uiComponent = mInputWidgets.get(field);
            EditText view = (EditText) uiComponent.getView();
            if (view != null) {
               view.setText(value);
            }
        }
    }

    private void init(Context context, ViewGroup rootView, FormOptions formOptions,
            ClientCacheManager cacheManager) {
        mContext = context;
        mRootView = rootView;
        mFormOptions = formOptions;
        mCacheData = new CacheData(cacheManager);
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mFormController =
            new FormController(new ClientData(mCacheData),
                               mWidgetLocale, mCurrentRegion);
        mFormatInterpreter = new FormatInterpreter(mFormOptions);
        mVerifier = new StandardAddressVerifier(
                new FieldVerifier(new ClientData(mCacheData)));
        if (!formOptions.isHidden(AddressField.COUNTRY)) {
            buildCountryListBox();
            createView(mRootView, mInputWidgets.get(AddressField.COUNTRY),
                    getLocalCountryName(mCurrentRegion),
                    formOptions.isReadonly(AddressField.COUNTRY));
        }
    }

    /**
     * Sets address data server URL. Input URL cannot be null.
     *
     * @param url The service URL.
     */
    public void setUrl(String url) {
        mCacheData.setUrl(url);
    }

    /**
     * Gets user input address in AddressData format.
     */
    public AddressData getAddressData() {
        AddressData.Builder builder = new AddressData.Builder();
        builder.setCountry(mCurrentRegion);
        for (AddressField field : mFormatInterpreter.getAddressFieldOrder(mScript,
                mCurrentRegion)) {
            AddressUiComponent addressUiComponent = mInputWidgets.get(field);
            if (addressUiComponent != null) {
                String value = addressUiComponent.getValue();
                if (addressUiComponent.getUiType() == UiComponent.SPINNER) {
                     // For drop-downs, return the key of the region selected instead of the value.
                     View view = getViewForField(field);
                     AddressSpinnerInfo spinnerInfo = findSpinnerByView(view);
                     if (spinnerInfo != null) {
                         value = spinnerInfo.getRegionDataKeyForValue(value);
                     }
                }
                builder.set(field, value);
            }
        }
        builder.setLanguageCode(mWidgetLocale);
        return builder.build();
    }

    /**
     * Gets the formatted address.
     *
     * This method does not validate addresses. Also, it will "normalize" the result strings by
     * removing redundant spaces and empty lines.
     *
     * @return the formatted address
     */
    public List<String> getEnvelopeAddress() {
        return mFormatInterpreter.getEnvelopeAddress(getAddressData());
    }

    /**
     * Gets the formatted address based on the AddressData passed in.
     */
    public List<String> getEnvelopeAddress(AddressData address) {
        return mFormatInterpreter.getEnvelopeAddress(address);
    }

    /**
     * Gets the formatted address based on the AddressData passed in with none of the relevant
     * fields hidden.
     */
    public static List<String> getFullEnvelopeAddress(AddressData address) {
        return new FormatInterpreter(SHOW_ALL_FIELDS).getEnvelopeAddress(address);
    }

    /**
     * Get problems found in the address data entered by the user.
     */
    public AddressProblems getAddressProblems() {
        AddressProblems problems = new AddressProblems();
        AddressData addressData = getAddressData();
        mVerifier.verify(addressData, problems);
        return problems;
    }

    /**
     * Displays an appropriate error message for an AddressField with a problem.
     *
     * @return the View object representing the AddressField.
     */
    public View displayErrorMessageForField(AddressData address,
            AddressField field, AddressProblemType problem) {
        Log.d(this.toString(), "Display error message for the field: " + field.toString());
        AddressUiComponent addressUiComponent = mInputWidgets.get(field);
        if (addressUiComponent != null && addressUiComponent.getUiType() == UiComponent.EDIT) {
            EditText view = (EditText) addressUiComponent.getView();
            view.setError(getErrorMessageForInvalidEntry(address, field, problem));
            return view;
        }
        return null;
    }

    private String getErrorMessageForInvalidEntry(AddressData address, AddressField field,
            AddressProblemType problem) {
        switch (problem) {
            case MISSING_REQUIRED_FIELD:
                return mContext.getString(R.string.i18n_missing_required_field);
            case UNKNOWN_VALUE:
                String currentValue = address.getFieldValue(field);
                return String.format(mContext.getString(R.string.unknown_entry), currentValue);
            case UNRECOGNIZED_FORMAT:
                // We only support this error type for the Postal Code field.
                return (mZipLabel == ZipLabel.POSTAL
                    ? mContext.getString(R.string.unrecognized_format_postal_code)
                    : mContext.getString(R.string.unrecognized_format_zip_code));
            case MISMATCHING_VALUE:
                // We only support this error type for the Postal Code field.
                return (mZipLabel == ZipLabel.POSTAL
                    ? mContext.getString(R.string.mismatching_value_postal_code)
                    : mContext.getString(R.string.mismatching_value_zip_code));
        }
        return "";
    }

    /**
     * Clears all error messages in the UI.
     */
    public void clearErrorMessage() {
        for (AddressField field : mFormatInterpreter.getAddressFieldOrder(mScript,
                mCurrentRegion)) {
            AddressUiComponent addressUiComponent = mInputWidgets.get(field);

            if (addressUiComponent != null && addressUiComponent.getUiType() == UiComponent.EDIT) {
                EditText view = (EditText) addressUiComponent.getView();
                if (view != null) {
                    view.setError(null);
                }
            }
        }
    }

    public View getViewForField(AddressField field) {
      AddressUiComponent component = mInputWidgets.get(field);
      if (component == null) {
        return null;
      }
      return component.getView();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        updateChildNodes(parent, position);
    }
}