如何获得接触的第一个名字,姓氏,针对Android单个查询电子邮件ID第一个、姓氏、如何获得、电子邮件

2023-09-07 02:49:44 作者:你已被我out

我想取名字,姓氏,从单一的查询电子邮件ID Android的联系人的详细信息。如果我通过获取以下过程的联系人。它正在采取很多时间获取和筛选。请给解决了这个解决方案。 presently我这样做这种方式。请看下面的到code。

 公共静态JSONArray getMABTosendServer(上下文的背景下,用户的UserBean,        DatabaseUserManager的UserManager)抛出JSONException {    hashedEmails =新的HashMap<弦乐,AddressBean>();    JSONArray jsonArray =新JSONArray();    HashMap的<字符串,字符串> emailValues​​ =新的HashMap<字符串,字符串>();    StringBuffer的SB =新的StringBuffer();    sb.append(......联系方式......);    ContentResolver的CR = context.getContentResolver();    光标CUR = cr.query(ContactsContract.Contacts.CONTENT_URI,空,            NULL,NULL,NULL);    串emailContact =;    串EMAILTYPE =;    光标nameCursor = NULL;    串的firstName =;    字符串的lastName =;    字符串ID = NULL;    长userLastContactId = 0;    INT I = 0;    如果(cur.getCount()大于0){        而(cur.moveToNext()){            我++;            ID = cur.getString(CUR                    .getColumnIndex(ContactsContract.Contacts._ID));            如果(用户= NULL和放大器;!&安培; user.getLastContactId()== NULL){                userLastContactId = 0;            }其他{                userLastContactId =的Long.parseLong(user.getLastContactId());            }            如果(的Long.parseLong(ID)> userLastContactId){                乌里contactUri = ContentUris.withAppendedId(                        Contacts.CONTENT_URI,的Long.parseLong(ID));                乌里dataUri = Uri.withAppendedPath(contactUri,                        Contacts.Data.CONTENT_DIRECTORY);                nameCursor = context.getContentResolver()查询(dataUri,                        空,Data.MIMETYPE +=?,                        新的String [] {} StructuredName.CONTENT_ITEM_TYPE,                        空值);                而(nameCursor.moveToNext()){                    的firstName = nameCursor.getString(nameCursor                            .getColumnIndex(Data.DATA2));                    的lastName = nameCursor.getString(nameCursor                            .getColumnIndex(Data.DATA3));                    光标emailCur = CR                            .query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,                                    空值,                                    ContactsContract.CommonDataKinds.Email.CONTACT_ID                                            +=?,新的String [] {ID},                                    空值);                    而(emailCur.moveToNext()){                        emailContact = emailCur                                .getString(emailCur                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));                        EMAILTYPE = emailCur                                .getString(emailCur                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));                        sb.append(\\ nEmail:+ emailContact +电子邮件类型:                                + EMAILTYPE);                        如果(EMAIL_ADDRESS_PATTERN.matcher(                                emailContact.trim())。匹配()                                &功放;&安培; !emailValues​​.containsKey(emailContact)){                            emailValues                                    。把(emailContact,将String.valueOf(i)段);                            的JSONObject的JSONObject =新的JSONObject();                            AddressBean AB =新AddressBean();                            如果(名字== NULL){                                的firstName =;                            }                            如果(lastName的== NULL){                                的lastName =;                            }                            ab.setFirstName(名字);                            ab.setLastName(lastName的);                            ab.setEmailId(emailContact);                            jsonObject.put(名字,名字);                            jsonObject.put(姓氏,姓氏);                            jsonObject.put(电子邮件,加密                                    .encryptUsingSha1(emailContact                                            。.toLowerCase()修剪()));                            hashedEmails.put(加密                                    .encryptUsingSha1(emailContact),AB);                            jsonArray.put(JSONObject的);                        }                    }                    emailCur.close();                }                nameCursor.close();            }        }        cur.close();        user.setLastContactId(ID);        userManager.updateUser(用户);    }    返回jsonArray;} 

解决方案

 公共类ReadContacts扩展的AsyncTask<太虚,太虚,太虚> {    私人的ListView contactsList;    私人语境CNTX;    私人恒定常数;    静态最后的String [] = CONTACTS_SUMMARY_PROJECTION新的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    };    私人长期的ContactID;    私人字符串DISPLAY_NAME;    私人字符串phoneNumber的;    私人的ArrayList< ContactsWrapper> contactWrap =新的ArrayList< ContactsWrapper>();    私人的HashMap<长,ArrayList的< ContactsWrapper>>地图=新的HashMap<长,ArrayList的< ContactsWrapper>>();    私人ContactsAdapter适配器;    私人DataController类控制器;    公共ReadContacts(上下文CNTX,ListView控件contactList){        // TODO自动生成构造函数存根        this.cntx = CNTX;        常量=新常数();        this.contactsList = contactList;        控制器= DataController.getInstance();    }    @覆盖    在preExecute保护无效(){        // TODO自动生成方法存根        super.on preExecute();        如果(!(controller.contactWrapper.size()&0))             constants.displayProgressDialog(CNTX加载通讯录...,请等待);    }    @覆盖    保护无效doInBackground(虚空...... PARAMS){        // TODO自动生成方法存根        如果(!(controller.contactWrapper.size()&0))        {        尝试{            串选择=((+ Contacts.DISPLAY_NAME +NOTNULL)AND(                    + Contacts.HAS_PHONE_NUMBER += 1)AND(                    + Contacts.DISPLAY_NAME +=''))!;            光标C = cntx.getContentResolver()查询(Contacts.CONTENT_URI,CONTACTS_SUMMARY_PROJECTION,选择,                    空,Contacts.DISPLAY_NAME +分页中局部ASC);            的for(int i = 0; I< c.getCount();我++)            {// contactWrap.clear();                尝试{                    的ContactID = 0;                    串hasPhone =;                    DISPLAY_NAME =;                    phoneNumber的=;                    c.moveToPosition(ⅰ);                    的ContactID = c.getLong(0);                    DISPLAY_NAME = c.getString(1);                    hasPhone = c.getString(7);                    如果(hasPhone.equalsIgnoreCase(1))                        hasPhone =真;                    其他                        hasPhone =假;                    如果(Boolean.parseBoolean(hasPhone))                    {                        。光标手机= cntx.getContentResolver()查询(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,空,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +=+的ContactID,NULL,NULL);                        而(phones.moveToNext())                        {                            INT indexPhoneType = phones.getColumnIndexOrThrow(Phone.TYPE);                            字符串PHONETYPE = phones.getString(indexPhoneType);                            phoneNumber的= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                            串lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));                            contactWrap.add(新ContactsWrapper(的ContactID,DISPLAY_NAME,phoneNumber的,lookupKey,FALSE));                        }// map.put(的ContactID,新的ArrayList< ContactsWrapper>(contactWrap));                        phones.close();                    }                }赶上(例外五){                    e.printStackTrace();                }            }            controller.contactWrapper = contactWrap;        }        赶上(例外五){            // TODO:处理异常            e.printStackTrace();        }        }        返回null;    }    @覆盖    保护无效onPostExecute(虚空结果){        // TODO自动生成方法存根        super.onPostExecute(结果);        constants.dismissDialog();        适配器=新ContactsAdapter(CNTX);        contactsList.setAdapter(适配器);    }} 

取名字软件下载安装 取名字最新版下载v2.0.0 安卓免费版 2265安卓网

i want to fetch android contacts details of firstname , lastname, email id from single query. if i fetch the contacts by below process. it is taking lot of time fetching and filtering. Please give the solution to solve this. Presently i am doing in this way . please look into below code.

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;
}

解决方案

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);
    }

}