0

我想从单个查询中获取名字、姓氏、电子邮件 ID 的 android 联系人详细信息。如果我通过以下过程获取联系人。获取和过滤需要花费大量时间。请给出解决方案来解决这个问题。目前我正在这样做。请查看下面的代码。

public static JSONArray getMABTosendServer(Context context, UserBean user,
        DatabaseUserManager userManager) throws JSONException {
    hashedEmails = new HashMap<String, AddressBean>();
    JSONArray jsonArray = new JSONArray();
    HashMap<String, String> emailValues = new HashMap<String, String>();

    StringBuffer sb = new StringBuffer();
    sb.append("......Contact Details.....");
    ContentResolver cr = context.getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null);
    String emailContact = "";
    String emailType = "";
    Cursor nameCursor = null;
    String firstName = "";
    String lastName = "";
    String id = null;
    long userLastContactId = 0;
    int i = 0;
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            i++;

            id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));
            if (user != null && user.getLastContactId() == null) {
                userLastContactId = 0;
            } else {
                userLastContactId = Long.parseLong(user.getLastContactId());
            }
            if (Long.parseLong(id) > userLastContactId) {
                Uri contactUri = ContentUris.withAppendedId(
                        Contacts.CONTENT_URI, Long.parseLong(id));
                Uri dataUri = Uri.withAppendedPath(contactUri,
                        Contacts.Data.CONTENT_DIRECTORY);
                nameCursor = context.getContentResolver().query(dataUri,
                        null, Data.MIMETYPE + "=?",
                        new String[] { StructuredName.CONTENT_ITEM_TYPE },
                        null);
                while (nameCursor.moveToNext()) {
                    firstName = nameCursor.getString(nameCursor
                            .getColumnIndex(Data.DATA2));
                    lastName = nameCursor.getString(nameCursor
                            .getColumnIndex(Data.DATA3));
                    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));
                        emailType = emailCur
                                .getString(emailCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                        sb.append("\nEmail:" + emailContact + "Email type:"
                                + emailType);
                        if (EMAIL_ADDRESS_PATTERN.matcher(
                                emailContact.trim()).matches()
                                && !emailValues.containsKey(emailContact)) {
                            emailValues
                                    .put(emailContact, String.valueOf(i));
                            JSONObject jsonObject = new JSONObject();
                            AddressBean ab = new AddressBean();

                            if (firstName == null) {
                                firstName = "";
                            }
                            if (lastName == null) {
                                lastName = "";
                            }
                            ab.setFirstName(firstName);
                            ab.setLastName(lastName);
                            ab.setEmailId(emailContact);
                            jsonObject.put("firstName", firstName);
                            jsonObject.put("lastName", lastName);
                            jsonObject.put("email", Encryption
                                    .encryptUsingSha1(emailContact
                                            .toLowerCase().trim()));
                            hashedEmails.put(Encryption
                                    .encryptUsingSha1(emailContact), ab);
                            jsonArray.put(jsonObject);
                        }

                    }
                    emailCur.close();
                }
                nameCursor.close();
            }
        }
        cur.close();
        user.setLastContactId(id);
        userManager.updateUser(user);
    }
    return jsonArray;
}
4

1 回答 1

1
public class ReadContacts extends AsyncTask<Void, Void, Void>{

    private ListView contactsList;

    private Context cntx;
    private Constant constants;

    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
        Contacts._ID, // 0
        Contacts.DISPLAY_NAME, // 1
        Contacts.STARRED, // 2
        Contacts.TIMES_CONTACTED, // 3
        Contacts.CONTACT_PRESENCE, // 4
        Contacts.PHOTO_ID, // 5
        Contacts.LOOKUP_KEY, // 6
        Contacts.HAS_PHONE_NUMBER, // 7
    };

    private long contactId;
    private String display_name;
    private String phoneNumber;

    private ArrayList<ContactsWrapper>contactWrap = new ArrayList<ContactsWrapper>();
    private HashMap<Long, ArrayList<ContactsWrapper>>map = new HashMap<Long, ArrayList<ContactsWrapper>>();

    private ContactsAdapter adapter;

    private DataController controller;

    public ReadContacts(Context cntx, ListView contactList) {
        // TODO Auto-generated constructor stub
        this.cntx = cntx;
        constants = new Constant();
        this.contactsList = contactList;

        controller = DataController.getInstance(); 
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        if(!(controller.contactWrapper.size()>0))
             constants.displayProgressDialog(cntx, "Loading Contacts...", "Please Wait");
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        if(!(controller.contactWrapper.size()>0))
        {
        try {
            String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
                    + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
                    + Contacts.DISPLAY_NAME + " != '' ))";

            Cursor c = cntx.getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,
                    null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

            for(int i=0;i<c.getCount();i++)
            {
//              contactWrap.clear();
                try {
                    contactId = 0;
                    String hasPhone = "";
                    display_name = "";
                    phoneNumber = "";

                    c.moveToPosition(i);

                    contactId =  c.getLong(0);
                    display_name = c.getString(1);
                    hasPhone = c.getString(7);

                    if (hasPhone.equalsIgnoreCase("1"))
                        hasPhone = "true";
                    else
                        hasPhone = "false" ;

                    if (Boolean.parseBoolean(hasPhone)) 
                    {
                        Cursor phones = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
                        while (phones.moveToNext()) 
                        {
                            int indexPhoneType = phones.getColumnIndexOrThrow(Phone.TYPE);
                            String phoneType =  phones.getString(indexPhoneType);

                            phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

                            String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));

                            contactWrap.add(new ContactsWrapper(contactId, display_name, phoneNumber,lookupKey,false));
                        }
//                      map.put(contactId, new ArrayList<ContactsWrapper>(contactWrap));
                        phones.close();
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                }  
            }
            controller.contactWrapper = contactWrap;
        }
        catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        constants.dismissDialog();

        adapter = new ContactsAdapter(cntx);
        contactsList.setAdapter(adapter);
    }

}
于 2013-10-31T06:24:18.933 回答