summaryrefslogtreecommitdiffstats
path: root/src/com/android/contacts/multipicker/ContactsFragment.java
blob: ac11f45fe5d3f011acffe63ad52baa92b228c6e3 (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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
/*
 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of The Linux Foundation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.android.contacts.multipicker;

import android.accounts.Account;
import android.app.Activity;
import android.app.ListFragment;
import android.content.AsyncQueryHandler;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsContract.RawContacts;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.AbsListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.android.contacts.activities.MultiPickContactsActivity;
import com.android.contacts.common.ContactPhotoManager;
import com.android.contacts.common.ContactPhotoManager.DefaultImageRequest;
import com.android.contacts.common.format.TextHighlighter;
import com.android.contacts.common.list.AccountFilterActivity;
import com.android.contacts.common.list.ContactsSectionIndexer;
import com.android.contacts.common.list.ContactListFilter;
import com.android.contacts.common.MoreContactUtils;
import com.android.contacts.common.SimContactsConstants;
import com.android.contacts.common.model.account.SimAccountType;
import com.android.contacts.common.util.ContactDisplayUtils;
import com.android.contacts.common.util.UriUtils;
import com.android.contacts.common.widget.CheckableImageView;
import com.android.contacts.list.ContactsPickMode;
import com.android.contacts.list.OnCheckListActionListener;
import com.android.contacts.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ContactsFragment extends ListFragment {
    private final static String TAG = "ContactsFragment";
    private final static boolean DEBUG = true;

    private static final String SORT_ORDER = " desc";

    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
            Contacts._ID, // 0
            Contacts.DISPLAY_NAME_PRIMARY, // 1
            Contacts.DISPLAY_NAME_ALTERNATIVE, // 2
            Contacts.PHOTO_ID, // 3
            Contacts.LOOKUP_KEY, // 4
            RawContacts.ACCOUNT_TYPE, // 5
            RawContacts.ACCOUNT_NAME, // 6
            Contacts.NAME_RAW_CONTACT_ID, // 7
            Contacts.PHOTO_THUMBNAIL_URI // 8
    };

    static final String CONTACTS_SELECTION = Contacts.IN_VISIBLE_GROUP + "=1";

    static final String PHONES_SELECTION = RawContacts.ACCOUNT_TYPE + "<>?";

    static final String[] PHONES_SELECTION_ARGS = {
            SimContactsConstants.ACCOUNT_TYPE_SIM
    };

    private static final String[] DATA_PROJECTION = new String[] {
            Data._ID, // 0
            Data.DATA1, // 1 Phone.NUMBER, Email.address
            Data.DATA2, // 2  phone.type
            Data.DATA3, // 3 Phone.LABEL
            Data.DISPLAY_NAME,// 4 Phone.DISPLAY_NAME
            Data.MIMETYPE, // 5
            Data.CONTACT_ID, // 6 Phone.CONTACT_ID
            RawContacts.ACCOUNT_TYPE, // 7
            RawContacts.ACCOUNT_NAME, // 8
            Contacts.LOOKUP_KEY, // 9
            Contacts.PHOTO_ID, // 10
            Contacts.PHOTO_THUMBNAIL_URI, // 11
    };

    // contacts column
    private static final int SUMMARY_ID_COLUMN_INDEX = 0;
    private static final int SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX = 1;
    private static final int SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX = 2;
    private static final int SUMMARY_PHOTO_ID_COLUMN_INDEX = 3;
    private static final int SUMMARY_LOOKUP_KEY_COLUMN_INDEX = 4;
    private static final int SUMMARY_ACCOUNT_TYPE = 5;
    private static final int SUMMARY_ACCOUNT_NAME = 6;
    private static final int SUMMARY_CONTACT_COLUMN_RAW_CONTACT_ID = 7;
    private static final int SUMMARY_CONTACT_COLUMN_PHOTO_URI = 8;
    // phone column
    private static final int PHONE_COLUMN_ID = 0;
    private static final int PHONE_COLUMN_NUMBER = 1;
    private static final int PHONE_COLUMN_TYPE = 2;
    private static final int PHONE_COLUMN_LABEL = 3;
    private static final int PHONE_COLUMN_DISPLAY_NAME = 4;
    private static final int PHONE_COLUMN_CONTACT_ID = 6;
    private static final int PHONE_ACCOUNT_TYPE = 7;
    private static final int PHONE_ACCOUNT_NAME = 8;
    private static final int PHONE_COLUMN_LOOKUP_KEY = 9;
    private static final int PHONE_COLUMN_PHOTO_ID = 10;
    private static final int PHONE_COLUMN_PHOTO_URI = 11;
    // email column
    private static final int EMAIL_COLUMN_ID = 0;
    private static final int EMAIL_COLUMN_ADDRESS = 1;
    private static final int EMAIL_COLUMN_DISPLAY_NAME = 4;
    // data column
    private static final int DATA_ID = 0;
    private static final int DATA_DATA1_COLUMN = 1;
    private static final int DATA_DATA2_COLUMN = 2;
    private static final int DATA_DATA3_COLUMN = 3;
    private static final int DATA_DISPLAY_NAME = 4;
    private static final int DATA_MIMETYPE_COLUMN = 5;
    private static final int DATA_CONTACT_ID = 6;

    private static final int QUERY_TOKEN = 43;

    public static final int ACTION_ADD_GROUP_MEMBER = 0;
    public static final int ACTION_MOVE_GROUP_MEMBER = 1;
    public static final int ACTION_DEFAULT_VALUE = -1;

    public static final String ADD_GROUP_MEMBERS = "add_group_members";

    public static final String ADD_MOVE_GROUP_MEMBER_KEY = "add_move_group_member";
    public static final String KEY_GROUP_ID = "group_id";

    private int subscription;

    private QueryHandler mQueryHandler;
    private Bundle mChoiceSet;
    private TextView mSelectAllLabel;

    private static final String KEY_SEP = ",";
    private static final String ITEM_SEP = ", ";
    private static final String CONTACT_SEP_LEFT = "[";
    private static final String CONTACT_SEP_RIGHT = "]";

    private Intent mIntent;
    private Context mContext;

    private ContactsPickMode mPickMode;
    private int mMode;

    private OnCheckListActionListener mCheckListListener;

    private ContactItemListAdapter mContactListAdapter;

    private String query;

    private String mFilter;

    private View mRootView;

    private SectionIndexer mIndexer;

    private View mHeaderView;

    // Only in pick phone mode, use this to count selected items number.
    private ArrayList<String> checkedList;

    private static final String[] COLUMN_NAMES = new String[] {
            "name",
            "number",
            "emails",
            "anrs",
            "_id"
    };

    private static final int SIM_COLUMN_DISPLAY_NAME = 0;
    private static final int SIM_COLUMN_NUMBER = 1;
    private static final int SIM_COLUMN_EMAILS = 2;
    private static final int SIM_COLUMN_ANRS = 3;
    private static final int SIM_COLUMN_ID = 4;

    /**
     * control of whether show the contacts in SIM card, if intent has this flag,not show.
     */
    private static final String EXT_NOT_SHOW_SIM_FLAG = "not_sim_show";

    /**
     * An item view is displayed differently depending on whether it is placed at the beginning,
     * middle or end of a section. It also needs to know the section header when it is at the
     * beginning of a section. This object captures all this configuration.
     */
    public static final class Placement {
        private int position = ListView.INVALID_POSITION;
        public boolean firstInSection;
        public boolean lastInSection;
        public String sectionHeader;

        public void invalidate() {
            position = ListView.INVALID_POSITION;
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (mContactListAdapter == null) {
            mContactListAdapter = new ContactItemListAdapter(mContext);
            if (mPickMode.isPickPhone()) {
                checkedList = new ArrayList<String>();
            }
        }
        mHeaderView = new View(mContext);
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT,
                (int)(mContext.getResources().getDimension(R.dimen.header_listview_height)));
        mHeaderView.setLayoutParams(layoutParams);
        getListView().addHeaderView(mHeaderView, null, false);
        setListAdapter(mContactListAdapter);
        mQueryHandler = new QueryHandler(mContext);
        startQuery();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mPickMode = ContactsPickMode.getInstance();
        mMode = mPickMode.getMode();
        mContext = (MultiPickContactsActivity) activity;
    }

    @Override
    public void onResume() {
        // ContactsPickMode is singleton, its mode may be changed by other mode.
        // need to reset
        mPickMode.setMode(mMode);
        super.onResume();
    }

    @Override
    public void onStop() {
        mMode = mPickMode.getMode();
        super.onStop();
    }

    public void setCheckListListener(OnCheckListActionListener checkListListener) {
        mCheckListListener = checkListListener;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        mCheckListListener.onHideSoftKeyboard();

        ContactItemCache cache = (ContactItemCache) v.getTag();
        String key = String.valueOf(cache.id);

        if (!mCheckListListener.onContainsKey(key)) {
            String[] value = null;
            if (mPickMode.isPickContact()) {
                value = new String[] {
                        cache.lookupKey, key,
                        String.valueOf(cache.nameRawContactId),
                        cache.photoUri == null ?
                        null : String.valueOf(cache.photoUri),
                        cache.name
                };
            } else if (mPickMode.isPickPhone()) {
                value = new String[] {
                        cache.name, cache.number,
                        cache.type, cache.label,
                        cache.contact_id
                };
                if (!checkedList.contains(key)) {
                    checkedList.add(key);
                }
            } else if (mPickMode.isPickEmail()) {
                value = new String[] {
                        cache.name,
                        cache.email
                };
            } else if (mPickMode.isPickSim()) {
                value = new String[] {
                        cache.name, cache.number,
                        cache.email, cache.anrs
                };
            } else if (mPickMode.isPickContactInfo()) {
                value = new String[] {
                        cache.contact_id, cache.name,
                        cache.number, cache.email
                };
            } else if (mPickMode.isPickContactVcard()) {
                value = new String[] {
                        cache.name,
                        cache.lookupKey
                };
            }
            mCheckListListener.putValue(key, value);
        } else {
            mCheckListListener.onRemove(key);
            if (mPickMode.isPickPhone()) {
                checkedList.remove(key);
            }
        }

        mCheckListListener.onUpdateActionBar();
        mCheckListListener.exitSearch();
        mContactListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mContext = null;
    }

    @Override
    public void onDestroy() {
        mQueryHandler.removeCallbacksAndMessages(QUERY_TOKEN);

        if (mContactListAdapter.getCursor() != null) {
            mContactListAdapter.getCursor().close();
        }

        super.onDestroy();
    }

    private Uri getUriToQuery() {
        Uri uri;
        switch (mPickMode.getMode()) {
            case ContactsPickMode.MODE_DEFAULT_CONTACT:
            case ContactsPickMode.MODE_SEARCH_CONTACT:
                mIntent = mPickMode.getIntent();
                int operation = mIntent.getIntExtra(ADD_MOVE_GROUP_MEMBER_KEY, -1);
                long groupId = mIntent.getLongExtra(KEY_GROUP_ID, -1);
                String accountName = mIntent.getStringExtra(SimContactsConstants.ACCOUNT_NAME);
                String accountType = mIntent.getStringExtra(SimContactsConstants.ACCOUNT_TYPE);
                switch (operation) {
                    case ACTION_ADD_GROUP_MEMBER:
                    case ACTION_MOVE_GROUP_MEMBER:
                        Builder builder = Contacts.CONTENT_GROUP_URI.buildUpon();
                        builder.appendQueryParameter(ADD_GROUP_MEMBERS, String.valueOf(
                                operation == ACTION_ADD_GROUP_MEMBER));
                        builder.appendQueryParameter(Groups._ID, String.valueOf(groupId));
                        builder.appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType);
                        builder.appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName);
                        uri = builder.build();
                        break;
                    default:
                        uri = Contacts.CONTENT_URI;
                        break;
                }
                break;
            case ContactsPickMode.MODE_DEFAULT_EMAIL:
            case ContactsPickMode.MODE_SEARCH_EMAIL:
                uri = Email.CONTENT_URI;
                break;
            case ContactsPickMode.MODE_DEFAULT_PHONE:
            case ContactsPickMode.MODE_SEARCH_PHONE:
                uri = Phone.CONTENT_URI;
                uri = uri.buildUpon().appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
                        String.valueOf(Directory.DEFAULT))
                        .appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "true")
                        .build();
                break;
            case ContactsPickMode.MODE_DEFAULT_SIM:
            case ContactsPickMode.MODE_SEARCH_SIM: {
                mIntent = mPickMode.getIntent();
                subscription = mIntent.getIntExtra(SimContactsConstants.SLOT_KEY,
                        SimContactsConstants.SLOT1);
                uri = querySimContacts(subscription);
            }
                break;
            case ContactsPickMode.MODE_DEFAULT_CONTACT_INFO:
            case ContactsPickMode.MODE_SEARCH_CONTACT_INFO:
                uri = Data.CONTENT_URI;
                break;
            case ContactsPickMode.MODE_DEFAULT_CONTACT_VCARD:
            case ContactsPickMode.MODE_SEARCH_CONTACT_VCARD:
                uri = Contacts.CONTENT_URI;
                break;
            default:
                throw new IllegalArgumentException("getUriToQuery: Incorrect mode: "
                        + mPickMode.getMode());
        }
        return uri.buildUpon().appendQueryParameter(Contacts.EXTRA_ADDRESS_BOOK_INDEX, "true")
                .build();
    }

    /**
     * Just get the uri we need to query contacts.
     *
     * @return uri with account info parameter if explicit request contacts fit current account,
     *         else just search contacts fit specified keyword.
     */
    private Uri getContactsFilterUri() {
        Uri filterUri = Contacts.CONTENT_FILTER_URI;

        // To confirm if the search rule must contain account limitation.
        Intent intent = mPickMode.getIntent();
        ContactListFilter filter = (ContactListFilter) intent
                .getParcelableExtra(AccountFilterActivity.KEY_EXTRA_CONTACT_LIST_FILTER);
        int operation = intent.getIntExtra(ADD_MOVE_GROUP_MEMBER_KEY, -1);
        long groupId = intent.getLongExtra(KEY_GROUP_ID, -1);
        String accountName = intent.getStringExtra(SimContactsConstants.ACCOUNT_NAME);
        String accountType = intent.getStringExtra(SimContactsConstants.ACCOUNT_TYPE);
        switch (operation) {
            case ACTION_ADD_GROUP_MEMBER:
            case ACTION_MOVE_GROUP_MEMBER:
                Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon();
                builder.appendQueryParameter(ADD_GROUP_MEMBERS,
                        String.valueOf(operation == ACTION_ADD_GROUP_MEMBER));
                builder.appendQueryParameter(Groups._ID, String.valueOf(groupId));
                builder.appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName);
                builder.appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType);
                return builder.build();
        }
        if (filter != null && filter.filterType == ContactListFilter.FILTER_TYPE_ACCOUNT) {

            // Need consider account info limitation, construct the uri with
            // account info query parameter.
            Builder builder = filterUri.buildUpon();
            filter.addAccountQueryParameterToUrl(builder);
            return builder.build();
        }

        if (!isShowSIM()) {
            filterUri = filterUri.buildUpon()
                    .appendQueryParameter(RawContacts.ACCOUNT_TYPE, SimAccountType.ACCOUNT_TYPE)
                    .appendQueryParameter(SimContactsConstants.WITHOUT_SIM_FLAG, "true").build();
        }
        // No need to consider account info limitation, just return a uri
        // with "filter" path.
        return filterUri;
    }

    private Uri getFilterUri() {
        switch (mPickMode.getMode()) {
            case ContactsPickMode.MODE_SEARCH_CONTACT:
                return getContactsFilterUri();
            case ContactsPickMode.MODE_SEARCH_PHONE:
                return Phone.CONTENT_FILTER_URI;
            case ContactsPickMode.MODE_SEARCH_EMAIL:
                return Email.CONTENT_FILTER_URI;
            default:
                log("getFilterUri: Incorrect mode: " + mPickMode.getMode());
        }
        return Contacts.CONTENT_FILTER_URI;
    }

    public String[] getProjectionForQuery() {
        switch (mPickMode.getMode()) {
            case ContactsPickMode.MODE_DEFAULT_CONTACT:
            case ContactsPickMode.MODE_SEARCH_CONTACT:
            case ContactsPickMode.MODE_DEFAULT_CONTACT_VCARD:
            case ContactsPickMode.MODE_SEARCH_CONTACT_VCARD:
                return CONTACTS_SUMMARY_PROJECTION;
            case ContactsPickMode.MODE_DEFAULT_PHONE:
            case ContactsPickMode.MODE_SEARCH_PHONE:
            case ContactsPickMode.MODE_DEFAULT_EMAIL:
            case ContactsPickMode.MODE_SEARCH_EMAIL:
            case ContactsPickMode.MODE_DEFAULT_CONTACT_INFO:
            case ContactsPickMode.MODE_SEARCH_CONTACT_INFO:
                return DATA_PROJECTION;
            case ContactsPickMode.MODE_DEFAULT_SIM:
            case ContactsPickMode.MODE_SEARCH_SIM:
                return COLUMN_NAMES;
            default:
                log("getProjectionForQuery: Incorrect mode: " + mPickMode.getMode());
        }
        return CONTACTS_SUMMARY_PROJECTION;
    }

    private String getSortOrder(String[] projection) {
        switch (mMode) {
            case ContactsPickMode.MODE_DEFAULT_CONTACT_INFO:
                return RawContacts.SORT_KEY_PRIMARY + " ," + RawContacts.CONTACT_ID + " ,"
                        + Data.MIMETYPE + SORT_ORDER;
            default:
                return RawContacts.SORT_KEY_PRIMARY;
        }
    }

    private String getSelectionForQuery() {
        switch (mPickMode.getMode()) {
            case ContactsPickMode.MODE_DEFAULT_EMAIL:
            case ContactsPickMode.MODE_SEARCH_EMAIL:
            case ContactsPickMode.MODE_DEFAULT_PHONE:
            case ContactsPickMode.MODE_SEARCH_PHONE:
                if (isShowSIM()) {
                    return null;
                } else {
                    return PHONES_SELECTION;
                }
            case ContactsPickMode.MODE_DEFAULT_CONTACT:
                return getSelectionForAccount();
            case ContactsPickMode.MODE_DEFAULT_SIM:
            case ContactsPickMode.MODE_SEARCH_SIM:
                return null;
            case ContactsPickMode.MODE_DEFAULT_CONTACT_INFO:
            case ContactsPickMode.MODE_SEARCH_CONTACT_INFO:
                return createEmailOrNumberSelection(query);
            default:
                return null;
        }
    }

    private String getSelectionForAccount() {
        @SuppressWarnings("deprecation")
        ContactListFilter filter = (ContactListFilter) mPickMode.getIntent()
                .getParcelableExtra(AccountFilterActivity.KEY_EXTRA_CONTACT_LIST_FILTER);
        if (filter == null) {
            return null;
        }
        switch (filter.filterType) {
            case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS:
                return null;
            case ContactListFilter.FILTER_TYPE_CUSTOM:
                return CONTACTS_SELECTION;
            case ContactListFilter.FILTER_TYPE_ACCOUNT:
                return null;
        }
        return null;
    }

    private String[] getSelectionArgsForQuery() {
        switch (mPickMode.getMode()) {
            case ContactsPickMode.MODE_DEFAULT_EMAIL:
            case ContactsPickMode.MODE_SEARCH_EMAIL:
            case ContactsPickMode.MODE_DEFAULT_PHONE:
            case ContactsPickMode.MODE_SEARCH_PHONE:
                if (isShowSIM()) {
                    return null;
                } else {
                    return PHONES_SELECTION_ARGS;
                }
            case ContactsPickMode.MODE_DEFAULT_SIM:
            case ContactsPickMode.MODE_SEARCH_SIM:
                return null;
            default:
                return null;
        }
    }

    private boolean isShowSIM() {
        // if airplane mode on, do not show SIM.
        return !mPickMode.getIntent().hasExtra(EXT_NOT_SHOW_SIM_FLAG);
    }

    public void startQuery() {
        Uri uri = getUriToQuery();
        ContactListFilter filter = (ContactListFilter) mPickMode.getIntent()
                .getParcelableExtra(AccountFilterActivity.KEY_EXTRA_CONTACT_LIST_FILTER);
        if (filter != null) {
            if (filter.filterType == ContactListFilter.FILTER_TYPE_ACCOUNT) {
                // We should exclude the invisiable contacts.
                uri = uri.buildUpon().appendQueryParameter(RawContacts.ACCOUNT_NAME,
                        filter.accountName)
                        .appendQueryParameter(RawContacts.ACCOUNT_TYPE,
                                filter.accountType)
                        .appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
                                ContactsContract.Directory.DEFAULT + "")
                        .build();
            } else if (filter.filterType == ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS) {
                // Do not query sim contacts in airplane mode.
                if (!isShowSIM()) {
                    uri = uri.buildUpon().appendQueryParameter(RawContacts.ACCOUNT_TYPE,
                            SimAccountType.ACCOUNT_TYPE)
                            .appendQueryParameter(SimContactsConstants.WITHOUT_SIM_FLAG,
                                    "true")
                            .build();
                }
            }
        }
        String[] projection = getProjectionForQuery();
        String selection = getSelectionForQuery();
        String[] selectionArgs = getSelectionArgsForQuery();
        mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, selection, selectionArgs,
                getSortOrder(projection));
    }

    public void doFilter(String s) {
        query = s;
        if (TextUtils.isEmpty(s)) {
            // mPickMode.exitSearchMode();
            // startQuery();
            mContactListAdapter.changeCursor(null);
            return;
        }

        Uri uri;
        if (mPickMode.isPickContactInfo()) {
            uri = Data.CONTENT_URI;
        } else {
            uri = Uri.withAppendedPath(getFilterUri(), Uri.encode(query));
        }
        String[] projection = getProjectionForQuery();
        String selection = getSelectionForQuery();
        String[] selectionArgs = getSelectionArgsForQuery();
        mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, selection, selectionArgs,
                getSortOrder(projection));
    }

    private class QueryHandler extends AsyncQueryHandler {
        protected WeakReference<ContactsFragment> mFragment;

        public QueryHandler(Context context) {
            super(context.getContentResolver());
            mFragment = new WeakReference<ContactsFragment>(
                    (ContactsFragment) ContactsFragment.this);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            // In the case of low memory, the WeakReference object may be
            // recycled.
            if (mFragment == null || mFragment.get() == null) {
                mFragment = new WeakReference<ContactsFragment>(ContactsFragment.this);
            }
            final ContactsFragment fragment = mFragment.get();
            if (mHeaderView != null && mPickMode.isSearchMode()) {
                getListView().removeHeaderView(mHeaderView);
            }
            mContactListAdapter.changeCursor(cursor);
        }
    }

    private class ContactItemCache {
        long id;
        String name;
        String number;
        String lookupKey;
        String type;
        String label;
        String contact_id;
        String email;
        String anrs;
        long nameRawContactId;
        Uri photoUri;
        Uri contactUri;
        long photoId;
    }

    public class ContactItemListAdapter extends CursorAdapter
            implements SectionIndexer, View.OnClickListener {
        protected LayoutInflater mInflater;
        private ContactPhotoManager mContactPhotoManager;
        private final TextHighlighter mTextHighlighter;

        private Placement mPlacementCache = new Placement();

        public ContactItemListAdapter(Context context) {
            super(context, null, false);

            mInflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mContactPhotoManager = ContactPhotoManager.getInstance(mContext);
            mTextHighlighter = new TextHighlighter(Typeface.BOLD);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ContactItemCache cache = (ContactItemCache) view.getTag();
            if (mPickMode.isPickContact()) {
                cache.id = cursor.getLong(SUMMARY_ID_COLUMN_INDEX);
                cache.lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX);
                cache.name = cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX);
                cache.nameRawContactId = cursor.getLong(SUMMARY_CONTACT_COLUMN_RAW_CONTACT_ID);
                ((TextView) view.findViewById(R.id.pick_contact_name))
                        .setText(cache.name == null ? "" : cache.name);
                view.findViewById(R.id.pick_contact_number).setVisibility(View.GONE);
                setPhotoView(view, cursor, cache);
                setHeaderAndHighLightIfNeed(view, cache, cursor);
            } else if (mPickMode.isPickPhone()) {
                cache.id = cursor.getLong(PHONE_COLUMN_ID);
                cache.name = cursor.getString(PHONE_COLUMN_DISPLAY_NAME);
                cache.number = cursor.getString(PHONE_COLUMN_NUMBER);
                cache.label = cursor.getString(PHONE_COLUMN_LABEL);
                cache.type = String.valueOf(cursor.getInt(PHONE_COLUMN_TYPE));
                ((TextView) view.findViewById(R.id.pick_contact_number)).setText(cache.number);

                setPhotoView(view, cursor, cache);
                setItemView(view, cursor, cache);
                setLabel(view, cursor);
                setHeaderAndHighLightIfNeed(view, cache, cursor);
            } else if (mPickMode.isPickSim()) {
                cache.id = cursor.getLong(SIM_COLUMN_ID);
                cache.name = cursor.getString(SIM_COLUMN_DISPLAY_NAME);
                cache.number = cursor.getString(SIM_COLUMN_NUMBER);
                cache.email = cursor.getString(SIM_COLUMN_EMAILS);
                cache.anrs = cursor.getString(SIM_COLUMN_ANRS);
                TextView mSimNameView = (TextView) view.findViewById(R.id.pick_contact_name);
                if (TextUtils.isEmpty(cache.name)) {
                    mSimNameView.setVisibility(View.GONE);
                } else {
                    mSimNameView.setVisibility(View.VISIBLE);
                    mSimNameView.setText(cache.name);
                }
                if (!TextUtils.isEmpty(cache.number)) {
                    ((TextView) view.findViewById(R.id.pick_contact_number)).setText(cache.number);
                } else if (!TextUtils.isEmpty(cache.email)) {
                    String[] emailArray = (cache.email).split(",");
                    ((TextView) view.findViewById(R.id.pick_contact_number)).setText(emailArray[0]);
                }
                setSimPhoto(view, cache);
            } else if (mPickMode.isPickEmail()) {
                cache.id = cursor.getLong(EMAIL_COLUMN_ID);
                cache.name = cursor.getString(EMAIL_COLUMN_DISPLAY_NAME);
                cache.email = cursor.getString(EMAIL_COLUMN_ADDRESS);
                ((TextView) view.findViewById(R.id.pick_contact_number)).setText(cache.email);
                setPhotoView(view, cursor, cache);
                setItemView(view, cursor, cache);
                setLabel(view, cursor);
                setHeaderAndHighLightIfNeed(view, cache, cursor);
            } else if (mPickMode.isPickContactInfo()) {
                cache.id = cursor.getLong(DATA_ID);
                cache.name = cursor.getString(DATA_DISPLAY_NAME);
                cache.type = cursor.getString(DATA_MIMETYPE_COLUMN);
                if (cache.type.equals(Phone.CONTENT_ITEM_TYPE)) {
                    cache.number = cursor.getString(DATA_DATA1_COLUMN);
                    ((TextView) view.findViewById(R.id.pick_contact_number)).setText(cache.number);
                } else if (cache.type.equals(Email.CONTENT_ITEM_TYPE)) {
                    cache.email = cursor.getString(DATA_DATA1_COLUMN);
                    ((TextView) view.findViewById(R.id.pick_contact_number)).setText(cache.email);
                }
                cache.label = cursor.getString(DATA_DATA3_COLUMN);
                cache.contact_id = cursor.getString(DATA_CONTACT_ID);

                setPhotoView(view, cursor, cache);
                setItemView(view, cursor, cache);
                setLabel(view, cursor);
                setHeaderAndHighLightIfNeed(view, cache, cursor);
            } else if (mPickMode.isPickContactVcard()) {
                cache.id = cursor.getLong(SUMMARY_ID_COLUMN_INDEX);
                cache.name = cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX);
                cache.lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX);
                ((TextView) view.findViewById(R.id.pick_contact_name))
                        .setText(cache.name == null ? "" : cache.name);
                ((TextView) view.findViewById(R.id.pick_contact_number))
                        .setVisibility(View.GONE);

                setPhotoView(view, cursor, cache);
                setHeaderAndHighLightIfNeed(view, cache, cursor);
            }

        }

        private void setHeaderAndHighLightIfNeed(View view, ContactItemCache cache,
                Cursor cursor) {
            if (mPickMode.isSearchMode()) {
                hideSectionHeader(view);
                if (!TextUtils.isEmpty(query)) {
                    setFilterHighLight(view, cache);
                }
            } else {
                bindSectionHeader(view, cursor.getPosition());
            }
        }

        private void setFilterHighLight(View view, ContactItemCache cache) {
            TextView nameView = (TextView) view.findViewById(R.id.pick_contact_name);
            CharSequence nameText = cache.name;
            nameText = mTextHighlighter.applyPrefixHighlight(nameText, query.toUpperCase());
            nameView.setText(nameText);

            TextView numberView = (TextView) view.findViewById(R.id.pick_contact_number);
            if (mPickMode.isPickEmail()) {
                CharSequence emailText = cache.email;
                emailText = mTextHighlighter.applyPrefixHighlight(emailText, query.toUpperCase());
                numberView.setText(emailText);
            } else if (mPickMode.isPickContactInfo()) {
                CharSequence infoText = null;
                if (cache.type.equals(Phone.CONTENT_ITEM_TYPE)) {
                    infoText = cache.number;
                } else if (cache.type.equals(Email.CONTENT_ITEM_TYPE)) {
                    infoText = cache.email;
                }
                infoText = mTextHighlighter.applyPrefixHighlight(infoText, query.toUpperCase());
                numberView.setText(infoText);
            } else {
                CharSequence numberText = cache.number;
                numberText = mTextHighlighter.applyPrefixHighlight(numberText, query.toUpperCase());
                numberView.setText(numberText);
            }
        }

        private void setLabel(View view, Cursor cursor) {
            TextView labelView = (TextView) view.findViewById(R.id.label);
            CharSequence label = null;
            int accountTypeIndex = cursor.getColumnIndexOrThrow(Phone.TYPE);
            int customLabelIndex = cursor.getColumnIndexOrThrow(Phone.LABEL);
            if (!cursor.isNull(accountTypeIndex)) {
                final int type = cursor.getInt(accountTypeIndex);
                final String customLabel = cursor.getString(customLabelIndex);

                label = Phone.getTypeLabel(mContext.getResources(), type, customLabel);
            }
            labelView.setText(label);
        }

        private void setItemView(View view, Cursor cursor, ContactItemCache cache) {
            CheckableImageView photoView = (CheckableImageView) view
                    .findViewById(R.id.pick_contact_photo);

            boolean isFirstEntry = true;
            int contactIdIndex = cursor.getColumnIndexOrThrow(Phone.CONTACT_ID);
            if (!cursor.isNull(contactIdIndex)) {
                long currentContactId = cursor.getLong(contactIdIndex);

                int position = cursor.getPosition();
                if (!cursor.isFirst() && cursor.moveToPrevious()) {
                    int preContactIdIndex = cursor.getColumnIndexOrThrow(Phone.CONTACT_ID);
                    if (!cursor.isNull(contactIdIndex)) {
                        final long previousContactId = cursor.getLong(preContactIdIndex);
                        if (currentContactId == previousContactId) {
                            isFirstEntry = false;
                        }
                    }
                }
                cursor.moveToPosition(position);
            }

            if (isFirstEntry) {
                view.getLayoutParams().height = mContext.getResources()
                        .getDimensionPixelSize(R.dimen.pick_contact_first_item_height);
                photoView.setVisibility(View.VISIBLE);
                view.findViewById(R.id.pick_contact_name).setVisibility(View.VISIBLE);
                ((TextView) view.findViewById(R.id.pick_contact_name))
                        .setText(cache.name == null ? "" : cache.name);
            } else {
                view.getLayoutParams().height = mContext.getResources()
                        .getDimensionPixelSize(R.dimen.pick_contact_same_item_height);
                if (mCheckListListener.onContainsKey(String.valueOf(cache.id))) {
                    photoView.setVisibility(View.VISIBLE);
                } else {
                    photoView.setVisibility(View.INVISIBLE);
                }
                view.findViewById(R.id.pick_contact_name).setVisibility(View.GONE);
            }
        }

        private void setSimPhoto(View view, ContactItemCache cache) {
            CheckableImageView photoView = ((CheckableImageView) view
                    .findViewById(R.id.pick_contact_photo));
            photoView.setVisibility(View.VISIBLE);

            Account account = null;
            //account = MoreContactUtils.getAcount(subscription);

            account = MoreContactUtils.getAcount(mContext, subscription);

            DefaultImageRequest request = new DefaultImageRequest(
                    "".equals(cache.name) ? null : cache.name, String.valueOf(cache.id), true);
            mContactPhotoManager.loadThumbnail(photoView, 0, account, false, true, request);

            photoView.setChecked(mCheckListListener.onContainsKey(String.valueOf(cache.id)),
                    false);
            if (photoView.isChecked()) {
                view.setActivated(true);
            } else {
                view.setActivated(false);
            }
        }

        private void hidePhotoView(View view) {
            CheckableImageView photoView = ((CheckableImageView) view
                    .findViewById(R.id.pick_contact_photo));
            photoView.setVisibility(View.GONE);
        }

        private void setPhotoView(View view, Cursor cursor, ContactItemCache cache) {
            CheckableImageView photoView = ((CheckableImageView) view
                    .findViewById(R.id.pick_contact_photo));
            photoView.setVisibility(View.VISIBLE);

            int photoIdIndex = cursor.getColumnIndexOrThrow(Contacts.PHOTO_ID);
            if (!cursor.isNull(photoIdIndex)) {
                cache.photoId = cursor.getLong(photoIdIndex);
            } else {
                cache.photoId = 0;
            }

            int photoUriIndex = cursor.getColumnIndexOrThrow(Contacts.PHOTO_THUMBNAIL_URI);
            if (!cursor.isNull(photoUriIndex)) {
                cache.photoUri = UriUtils.parseUriOrNull(cursor.getString(photoUriIndex));
            } else {
                cache.photoUri = null;
            }

            Account account = null;
            int accountNameIndex = cursor.getColumnIndexOrThrow(RawContacts.ACCOUNT_NAME);
            int accoutTypeIndex = cursor.getColumnIndexOrThrow(RawContacts.ACCOUNT_TYPE);
            if (!cursor.isNull(accoutTypeIndex) && !cursor.isNull(accountNameIndex)) {
                final String accountType = cursor.getString(accoutTypeIndex);
                final String accountName = cursor.getString(accountNameIndex);
                account = new Account(accountName, accountType);
            }

            if (cache.photoId != 0) {
                mContactPhotoManager.loadThumbnail(photoView, cache.photoId, account, false, true,
                        null);
            } else {
                final Uri photoUri = cache.photoUri == null ? null : cache.photoUri;
                DefaultImageRequest request = null;
                if (photoUri == null) {
                    cache.lookupKey = cursor
                            .getString(cursor.getColumnIndexOrThrow(Contacts.LOOKUP_KEY));
                    request = new DefaultImageRequest(cache.name, cache.lookupKey, true);
                }
                mContactPhotoManager.loadDirectoryPhoto(photoView, photoUri, account, false, true,
                        request);
            }

            photoView.setChecked(mCheckListListener.onContainsKey(String.valueOf(cache.id)), false);

            if ((mPickMode.isPickContact() || mPickMode.isPickContactVcard())) {
                if (!photoView.isChecked()) {
                    long contactId = cursor.getLong(cursor.getColumnIndexOrThrow(Contacts._ID));
                    String lookupKey = cursor
                            .getString(cursor.getColumnIndexOrThrow(Contacts.LOOKUP_KEY));
                    cache.contactUri = Contacts.getLookupUri(contactId, lookupKey);
                    photoView.setTag(cache);
                    photoView.setOnClickListener(this);
                } else {
                    photoView.setOnClickListener(null);
                    photoView.setClickable(false);
                }
            }

            if (photoView.isChecked()) {
                view.setActivated(true);
            } else {
                view.setActivated(false);
            }
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = null;
            v = mInflater.inflate(R.layout.multi_pick_contact_item, parent, false);
            ContactItemCache dataCache = new ContactItemCache();
            v.setTag(dataCache);
            return v;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View v;

            if (!getCursor().moveToPosition(position)) {
                throw new IllegalStateException("couldn't move cursor to position " + position);
            }

            if (convertView != null && convertView.getTag() != null) {
                v = convertView;
            } else {
                v = newView(mContext, getCursor(), parent);
            }
            bindView(v, mContext, getCursor());
            return v;
        }

        @Override
        public void changeCursor(Cursor cursor) {
            super.changeCursor(cursor);
            updateIndexer(cursor);
        }

        @Override
        public void onClick(View v) {
            ContactItemCache cache = (ContactItemCache) v.getTag();
            int clickId = v.getId();
            switch (clickId) {
                case R.id.pick_contact_photo:
                    if (cache != null && cache.contactUri != null) {
                        QuickContact.showQuickContact(mContext, v, cache.contactUri,
                                null, Phone.CONTENT_ITEM_TYPE);
                    }
                    break;
                default:
                    throw new IllegalStateException("this click is valid");
            }
        }

        private void bindSectionHeader(View view, int position) {
            TextView section = (TextView) view.findViewById(R.id.section_index);
            section.setVisibility(View.VISIBLE);
            Placement placement = getItemPlacementInSection(position);
            section.setText(placement.sectionHeader);
        }

        private void hideSectionHeader(View view) {
            TextView section = (TextView) view.findViewById(R.id.section_index);
            section.setVisibility(View.GONE);
        }

        /**
         * Updates the indexer, which is used to produce section headers.
         */
        private void updateIndexer(Cursor cursor) {
            if (cursor == null) {
                setIndexer(null);
                return;
            }

            Bundle bundle = cursor.getExtras();
            if (bundle.containsKey(Contacts.EXTRA_ADDRESS_BOOK_INDEX_TITLES)
                    && bundle.containsKey(Contacts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS)) {
                String sections[] = bundle.getStringArray(Contacts.EXTRA_ADDRESS_BOOK_INDEX_TITLES);
                int counts[] = bundle.getIntArray(Contacts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS);
                setIndexer(new ContactsSectionIndexer(sections, counts));
            } else {
                setIndexer(null);
            }
        }

        public void setIndexer(SectionIndexer indexer) {
            mIndexer = indexer;
            mPlacementCache.invalidate();
        }

        public Object[] getSections() {
            if (mIndexer == null) {
                return new String[] {
                        " "
                };
            } else {
                return mIndexer.getSections();
            }
        }

        /**
         * @return relative position of the section in the indexed partition
         */
        public int getPositionForSection(int sectionIndex) {
            if (mIndexer == null) {
                return -1;
            }

            return mIndexer.getPositionForSection(sectionIndex);
        }

        /**
         * @param position relative position in the indexed partition
         */
        public int getSectionForPosition(int position) {
            if (mIndexer == null) {
                return -1;
            }

            return mIndexer.getSectionForPosition(position);
        }

        /**
         * Computes the item's placement within its section and populates the {@code placement}
         * object accordingly. Please note that the returned object is volatile and should be copied
         * if the result needs to be used later.
         */
        public Placement getItemPlacementInSection(int position) {
            if (mPlacementCache.position == position) {
                return mPlacementCache;
            }

            mPlacementCache.position = position;
            int section = getSectionForPosition(position);
            if (section != -1 && getPositionForSection(section) == position) {
                mPlacementCache.firstInSection = true;
                mPlacementCache.sectionHeader = (String) getSections()[section];
            } else {
                mPlacementCache.firstInSection = false;
                mPlacementCache.sectionHeader = null;
            }

            mPlacementCache.lastInSection = (getPositionForSection(section + 1) - 1 == position);
            return mPlacementCache;
        }
    }

    protected static void log(String msg) {
        if (DEBUG)
            Log.d(TAG, msg);
    }

    private Uri querySimContacts(int subscription) {
        Uri uri = null;
        TelephonyManager tm = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (subscription != SimContactsConstants.SLOT1
                && subscription != SimContactsConstants.SLOT2) {
            return uri;
        }
        int subId = MoreContactUtils.getActiveSubId(mContext, subscription);
        if (subId > 0 && tm.getPhoneCount() > 1) {
            uri = Uri.parse(SimContactsConstants.SIM_SUB_URI + subId);
        }
        else {
            uri = Uri.parse(SimContactsConstants.SIM_URI);
        }

        return uri;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
        mRootView = inflater.inflate(R.layout.multi_pick_contacts_fragment, container, false);
        return mRootView;
    }

    // support filter email and phone types together
    private String createEmailOrNumberSelection(String s) {
        StringBuilder selection = new StringBuilder();
        selection.append("(");
        selection
                .append(Data.MIMETYPE + "='"
                        + Email.CONTENT_ITEM_TYPE + "'")
                .append(" OR ")
                .append(Data.MIMETYPE + "='"
                        + Phone.CONTENT_ITEM_TYPE + "'");
        selection.append(")");
        if (s == null || !mPickMode.isSearchMode()) {
            return selection.toString();
        }
        selection.append(" AND ");
        selection.append("(");
        selection.append(Data.CONTACT_ID);
        selection.append(" IN ");
        queryContactsIDByFilter(selection, s);
        selection.append(")");
        return selection.toString();
    }

    private void queryContactsIDByFilter(StringBuilder sb, String query) {
        Uri uri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, query);
        Cursor cursor = getActivity().getContentResolver().query(uri, new String[]{Contacts._ID},
                null, null, null);
        sb.append("( ");
        if (cursor != null && cursor.getCount() != 0) {
            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                int contact_id = cursor.getInt(0);
                sb.append(contact_id);
                sb.append(",");
            }
            cursor.close();
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append(")");
    }

    /**
     * @param isSelectedAll isSelectedAll is true, selected all contacts
     * isSelectedAll is False, deselected all contacts
     */
    public void setSelectedAll(boolean isSelectedAll) {
        Cursor cursor = mContactListAdapter.getCursor();
        if (cursor == null) {
            return;
        }
        ContactItemCache cache = new ContactItemCache();
        String key;
        // selected all contacts
        if (isSelectedAll) {
            int count = cursor.getCount();
            for (int i = 0; i < count; i++) {
                cursor.moveToPosition(i);
                // only pick sim mode, id index is SIM_COLUMN_ID
                // other mode, id index is 0
                if (mPickMode.isPickSim()) {
                    key = String.valueOf(cursor.getLong(SIM_COLUMN_ID));
                } else {
                    key = String.valueOf(cursor.getLong(0));
                }
                if (!mCheckListListener.onContainsKey(key)) {
                    String[] value = null;
                    if (mPickMode.isPickContact()) {
                        cache.lookupKey = cursor
                                .getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX);
                        cache.name = cursor
                                .getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX);
                        cache.nameRawContactId = cursor
                                .getLong(SUMMARY_CONTACT_COLUMN_RAW_CONTACT_ID);
                        String photoUri = cursor.getString(SUMMARY_CONTACT_COLUMN_PHOTO_URI);
                        cache.photoUri = UriUtils.parseUriOrNull(photoUri);
                        value = new String[] {
                                cache.lookupKey,
                                key, String.valueOf(cache.nameRawContactId),
                                photoUri, cache.name
                        };
                    } else if (mPickMode.isPickPhone()) {
                        cache.name = cursor
                                .getString(PHONE_COLUMN_DISPLAY_NAME);
                        cache.number = cursor.getString(PHONE_COLUMN_NUMBER);
                        cache.label = cursor.getString(PHONE_COLUMN_LABEL);
                        cache.type = String.valueOf(cursor
                                .getInt(PHONE_COLUMN_TYPE));
                        value = new String[] {
                                cache.name, cache.number,
                                cache.type, cache.label, cache.contact_id
                        };
                        if (!checkedList.contains(key)) {
                            checkedList.add(key);
                        }
                    } else if (mPickMode.isPickEmail()) {
                        cache.name = cursor
                                .getString(EMAIL_COLUMN_DISPLAY_NAME);
                        cache.email = cursor.getString(EMAIL_COLUMN_ADDRESS);
                        value = new String[] {
                                cache.name, cache.email
                        };
                    } else if (mPickMode.isPickSim()) {
                        cache.name = cursor.getString(SIM_COLUMN_DISPLAY_NAME);
                        cache.number = cursor.getString(SIM_COLUMN_NUMBER);
                        cache.email = cursor.getString(SIM_COLUMN_EMAILS);
                        cache.anrs = cursor.getString(SIM_COLUMN_ANRS);
                        value = new String[] {
                                cache.name, cache.number,
                                cache.email, cache.anrs
                        };
                    } else if (mPickMode.isPickContactInfo()) {
                        cache.name = cursor.getString(DATA_DISPLAY_NAME);
                        cache.type = cursor.getString(DATA_MIMETYPE_COLUMN);
                        if (cache.type.equals(Phone.CONTENT_ITEM_TYPE)) {
                            cache.number = cursor.getString(DATA_DATA1_COLUMN);
                        } else if (cache.type.equals(Email.CONTENT_ITEM_TYPE)) {
                            cache.email = cursor.getString(DATA_DATA1_COLUMN);
                        }
                        cache.label = cursor.getString(DATA_DATA3_COLUMN);
                        cache.contact_id = cursor.getString(DATA_CONTACT_ID);
                        value = new String[] {
                                cache.contact_id, cache.name,
                                cache.number, cache.email
                        };
                    } else if (mPickMode.isPickContactVcard()) {
                        cache.name = cursor.getString(SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX);
                        cache.lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX);
                        value = new String[] {
                                cache.name, cache.lookupKey
                        };
                    }
                    mCheckListListener.putValue(key, value);
                }
            }
        } else {
            // deselected all contacts
            if (!mPickMode.isPickPhone()) {
                mCheckListListener.onClear();
            } else {
                int count = cursor.getCount();
                for (int i = 0; i < count; i++) {
                    cursor.moveToPosition(i);
                    key = String.valueOf(cursor.getLong(PHONE_COLUMN_ID));
                    if (mCheckListListener.onContainsKey(key)) {
                        mCheckListListener.onRemove(key);
                    }
                }
                // clear checked item numbers
                checkedList.clear();
            }
        }

        // update actionbar selected button to display selected item numbers
        mCheckListListener.onUpdateActionBar();
        mContactListAdapter.notifyDataSetChanged();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            // initialization contactsFragme page, ensure that check contact item is selected
            if (checkedList != null) {
                mContactListAdapter.notifyDataSetChanged();
                Cursor mCursor = mContactListAdapter.getCursor();
                if (mCursor == null)
                    return;
                for (int i = 0; i < mCursor.getCount(); i++) {
                    mCursor.moveToPosition(i);
                    String key;
                    if (mPickMode.isPickSim()) {
                        key = String.valueOf(mCursor.getLong(SIM_COLUMN_ID));
                    } else {
                        key = String.valueOf(mCursor.getLong(0));
                    }
                    if (mCheckListListener.onContainsKey(key)) {
                        if (mPickMode.isPickPhone()) {
                            if (!checkedList.contains(key)) {
                                checkedList.add(key);
                            }
                        }
                    } else {
                        if (checkedList.contains(key)) {
                            checkedList.remove(key);
                        }
                    }
                }
                mCheckListListener.onUpdateActionBar();
            }
        }
    }

    public int getAllCheckedListSize() {
        return checkedList.size();
    }

}