Contact fetching takes too much time

落爺英雄遲暮 提交于 2020-01-23 20:44:55

问题


In my code the contact fetching takes too much time to fetch the contacts and show in the application. Please guide me where i am wrong and what should i correct in order to make execution time fast.

Here is my code.

ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null );
    String phone = null;
    List<String> phonenumber = new ArrayList<String>();
    String emailContact = null;
    String emailType = null;
    String image_uri = "";
    Bitmap bitmap = null;
    if (cur.getCount() > 0) {
        while (cur.moveToNext())
        {
            String id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur
                    .getString(cur
                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            image_uri = cur
                    .getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
            if (Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
            {
                System.out.println("name : " + name + ", ID : " + id);

                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + " = ?", new String[]{id}, null);
                Log.e("pCur","dfgfdg  "+pCur.getCount());
                while (pCur.moveToNext())
                {
                        phone = pCur
                                .getString(pCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    // contactid=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                   /* phonenumber.add(pCur
                            .getString(pCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));`*/
                   Log.e("phone" ,phone);

                }
                pCur.close();


                Cursor emailCur = cr.query
                        (
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                + " = ?", new String[]{id}, null);

                while (emailCur.moveToNext())
                {
                    emailContact = emailCur
                            .getString(emailCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                    if(TextUtils.isEmpty(emailContact)||emailContact.equalsIgnoreCase(null)||emailContact.equalsIgnoreCase(""))
                    {
                        emailContact="";

                        Log.e("isEmpty","isEmpty " + emailContact);
                    }

                    else
                    {
                        Log.e("gfdszfg","Email " + emailContact);
                    }
                  /*  emailType = emailCur
                            .getString(emailCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));*/

                    Log.e("gfdszfg","Email " + emailContact);
                }
                emailCur.close();
            }

            if (image_uri != null)
            {
                System.out.println(Uri.parse(image_uri));
                try
                {
                    bitmap = MediaStore.Images.Media
                            .getBitmap(this.getContentResolver(),
                                    Uri.parse(image_uri));
                    System.out.println(bitmap);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            mList.add(new Contacts(name, phone, image_uri,emailContact));
            emailContact="";
        }
        cur.close();
        mMyContactsAdapter = new MyContactsAdapter(MainActivity.this, mList);
        mcontact.setAdapter(mMyContactsAdapter);
    }

and more over in my code my contact fetching while loop is looping 3 times i dont know why.


回答1:


I have faced this situation as you are in right now. Try below code

public static ArrayList ReadContactsSpecialWay(Context context) {
    StringBuffer contactBuffer = new StringBuffer();
    StringBuffer emailBuffer = new StringBuffer();

    ArrayList<String> contactList = new ArrayList<>();
    ArrayList<String> emailList = new ArrayList<>();
    ArrayList<ContactModel> contactModelsList = new ArrayList<>();
    HashMap<Integer, Boolean> hashMap = new HashMap<Integer, Boolean>();
    String[] emailsAndContacts = new String[2];

    // Phone numbers
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] projection = new String[]{
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
    };

    Cursor phoneNumbers = context.getContentResolver().query(uri, projection, null, null, null);
    int indexContactID = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
    int indexName = phoneNumbers.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
    int indexNumber = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    while (phoneNumbers.moveToNext()) {
        Integer contactId = phoneNumbers.getInt(indexContactID);
        String contactName = phoneNumbers.getString(indexName);
        String contactNumber = phoneNumbers.getString(indexNumber).replace(" ", "");

        ContactModel contactModel = new ContactModel();
        contactModel.setContactPhone(contactNumber);
        contactNumber = contactModel.getContactPhone();

        if (hashMap.containsKey(contactId))
            contactModel.setContactName(contactName + " (" + contactNumber + ")");
        else {
            hashMap.put(contactId, true);
            contactModel.setContactName(contactName);
        }
        contactModelsList.add(contactModel);
        contactList.add(contactNumber);
        LogHelper.informationLog(contactNumber + "   " + contactName);
        contactBuffer.append(contactNumber + ",");
    }
    phoneNumbers.close();

    // Emails
    uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
    projection = new String[]{
            ContactsContract.CommonDataKinds.Email.CONTACT_ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Email.DATA
    };
    Cursor emails = context.getContentResolver().query(uri, projection, null, null, null);
    indexContactID = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
    indexName = emails.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
    int indexData = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
    while (emails.moveToNext()) {
        Integer contactId = emails.getInt(indexContactID);
        String contactName = emails.getString(indexName);
        String contactEmail = emails.getString(indexData).toLowerCase();
        ContactModel contactModel = new ContactModel();
        contactModel.setEmailAddress(contactEmail);

        if (hashMap.containsKey(contactId)) {
            contactModel.setEmailName(contactName + " (" + contactEmail + ")");
        } else {
            contactModel.setEmailName(contactName);
            hashMap.put(contactId, true);
        }
        contactModelsList.add(contactModel);

        if (contactEmail != null && !emailList.contains(contactEmail)) {
            emailList.add(contactEmail);
            LogHelper.informationLog(contactEmail + "   " + contactName);
            emailBuffer.append(contactEmail + ",");
        }
    }
    emails.close();

    if (contactBuffer.toString().length() > 0) {
        emailsAndContacts[0] = contactBuffer.toString().substring(0, (contactBuffer.toString().length() - 1));
    } else
        emailsAndContacts[0] = "";

    if (emailBuffer.toString().length() > 0) {
        emailsAndContacts[1] = emailBuffer.toString();
    } else {
        emailsAndContacts[1] = "";
    }

    if(contactModelsList.size() == 0)
        return null;
    else {
        ArrayList specialList = new ArrayList();
        specialList.add(contactModelsList);
        specialList.add(emailsAndContacts);

        return specialList;
    }
}

It will definitely help you out.




回答2:


Try this, using AsyncTask. Use it while launching apps default activity on background and fetch the array while using on another activity

class LoadContact extends AsyncTask<Void, Void, Void> {
    @Override

    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        // Get Contact list from Phone

        Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;

        String _ID = ContactsContract.Contacts._ID;

        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
        Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

        String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;

        String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

        ContentResolver contentResolver = getContentResolver();

        /**
         * @discussion Query contact and return name and contact Id.
         */
        Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Bitmap bit_thumb = null;

                String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
                String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));

                String image_thumb = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
                try {
                    if (image_thumb != null) {
                        bit_thumb = MediaStore.Images.Media.getBitmap(contentResolver, Uri.parse(image_thumb));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }


                while (phoneCursor.moveToNext()) {
                    String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));

                    final SelectUser selectUser = new SelectUser();
                    selectUser.setName(name);
                    selectUser.setContactId(contact_id + "" + phoneNumber);
                    selectUser.setThumb(bit_thumb);
                    selectUser.setPhone(phoneNumber);
                    if (selectUser.getPhone() != null && selectUser.getPhone().length() > 0 && !num.equalsIgnoreCase(phoneNumber)) {
                        num = phoneNumber;
                        selectUsers.add(selectUser);
                    }
                }
                phoneCursor.close();
                Cursor cur1 = contentResolver.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                        new String[]{contact_id}, null);
                while (cur1.moveToNext()) {
                    String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    final SelectUser selectUser = new SelectUser();
                    selectUser.setName(name);
                    selectUser.setContactId(contact_id + "" + email);
                    selectUser.setThumb(bit_thumb);
                    selectUser.setEmail(email);
                    if (selectUser.getEmail() != null && selectUser.getEmail().length() > 0 && !userEmail.equalsIgnoreCase(email)) {
                        userEmail=email;
                        selectUsers.add(selectUser);
                    }
                }
                cur1.close();


            }
        }
        cursor.close();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        isContactLoaded = true;

    }
}


来源:https://stackoverflow.com/questions/42250015/contact-fetching-takes-too-much-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!