如何一次查询联系人的所有详细信息

Posted

技术标签:

【中文标题】如何一次查询联系人的所有详细信息【英文标题】:How to query all the details of the Contact at once 【发布时间】:2013-11-11 09:24:11 【问题描述】:

编辑:我认为重要的联系方式的列表:

1.NAME
2.PHONE NUMBER
3.EMAIL ADDRESS
4.WEBSITE
5.PHYSICAL ADDRESS 

我更愿意使用预取的联系人 ID 来执行此操作...仅使用一个游标来获取所有指定的数据。我希望找到正确的查询来执行此操作:

我想一次获取联系人的所有重要详细信息,我正在使用以下代码来执行此操作:

       public void getAllDataByContactId(int contactId)

    Log.d(TAG, "Seriously scared it might not work");
    String phoneNo="Phone disconnected";
    String email="Email could not be delivered";
    String website="Website 404";
    String address="Number 13,Dark Street,Area 51,Bermuda Trianlge";
    String name="Clint Eastwood";
    int hasPhoneNumber;
    String selection=ContactsContract.Data.CONTACT_ID+"=?";
    String[] selectionArgs=String.valueOf(contactId);
    Cursor c=context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null,selection, selectionArgs,ContactsContract.Data.TIMES_CONTACTED);

    if(c!=null && c.getCount()>0)
    

        while(c.moveToNext())
        

            phoneNo=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.d(TAG, "Phone number: "+phoneNo);
            email=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
            Log.d(TAG, "Email: "+email);
            website=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
            Log.d(TAG, "Website :"+website);
            address=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
            name=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
            Log.d(TAG, "Name :"+name);
        
       

但是,尽管这不会引发错误,但它会显示许多行,其中包含一个空字符串,其中夹杂着实际值。如何编写一个消除噪音的查询?

我已经尝试过了,这让我得到了所有的价值:

             String selection=ContactsContract.Data.CONTACT_ID+"=? AND "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=?";
    String[] selectionArgs=String.valueOf(contactId),ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE;

【问题讨论】:

亲爱的你做了吗... 您是在说我需要使用多个游标来检索我需要获取的数据(电话号码、电子邮件、网站...)并将数据存储在包装器中。有没有办法通过调整文章末尾提到的选择条款来获取数据? 从这里你得到亲爱的我关注相同的 4 联系人 但这不意味着 1 个用于手机的光标、一个用于电子邮件的光标、一个用于网站的光标等...我相信使用 SQL 可以同时显示来自各种表的数据...可以这样吗使用单个光标完成...我有方便的方法可以使用每个项目的光标获取所有详细信息。 亲爱的我只用了一个请仔细看我的代码 【参考方案1】:

回答为时已晚,但也许它可以帮助将来的人。 我对这个问题的解决方案只有一个 while 循环和查询:

private void fetchContacts(ContentResolver contentResolver) 
        if (contentResolver == null) return;

        Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI,
                null, null, null, null);

        if (cursor == null || cursor.getCount() <= 0) 
            return;
        

        String prevId = "";
        String contactId = "";
        PersonContact personContact = null;
        while (cursor.moveToNext()) 
            String company = "";
            String columnName = cursor.getString(cursor.getColumnIndex("mimetype"));
            if (columnName.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)) 
                company = cursor.getString(cursor.getColumnIndex("data1"));
            

            String email = "";
            if (columnName.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) 
                email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            
            String phone = "";
            if (columnName.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) 
                phone = cursor.getString(cursor.getColumnIndex("data1"));
            
            String first = "";
            String last = "";
            if (columnName.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) 
                first = cursor.getString(cursor.getColumnIndex("data2"));
                last = cursor.getString(cursor.getColumnIndex("data3"));
            

            if (!prevId.equals(contactId)) 
                if (!TextUtils.isEmpty(prevId)) 
                    addFilteredList(personContact);
                    allContacts.put(prevId, personContact);
                
                prevId = contactId;
                personContact = new PersonContact();
             else 
                if (personContact != null) 
                    personContact.id = prevId;
                    if (TextUtils.isEmpty(personContact.company)) personContact.company = company;
                    if (TextUtils.isEmpty(personContact.firstName)) personContact.firstName = first;
                    if (TextUtils.isEmpty(personContact.lastName)) personContact.lastName = last;
                    if (!TextUtils.isEmpty(email) && personContact.emails.size() == 0) 
                        personContact.emails.add(email);
                    
                    if (!TextUtils.isEmpty(phone) && personContact.phoneNumbers.size() == 0) 
                        personContact.phoneNumbers.add(phone);
                    
                
            

            contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
        
        cursor.close();
    

如您所见,我使用了 prevId 字段,因为 cursor.moveToNext 对一个联系人执行多次(一次用于名字和姓氏,一次用于电话等)。每次迭代后,我都会检查之前的联系人标识符和当前标识符,如果为假,我会更新 personContact 模型中的字段。

【讨论】:

【参考方案2】:

可能不是最好的解决方案。但这就是我实现它的方式。

ArrayList<String> fnameList = new ArrayList<>();
    ArrayList<String> lnameList = new ArrayList<>();
    ArrayList<String> mnumList = new ArrayList<>();
    ArrayList<String> hnumList = new ArrayList<>();
    ArrayList<String> wnumList = new ArrayList<>();
    ArrayList<String> mailList = new ArrayList<>();

    final DynamoDBMapper dynamoDBMapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    final ContactsDO firstItem = new ContactsDO(); // Initialize the Notes Object

    firstItem.setUserId(AWSMobileClient.defaultMobileClient().getIdentityManager().getCachedUserID());
    String email = null;

    Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
    String _ID = ContactsContract.Contacts._ID;
    String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

    Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
    String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
    String DATA = ContactsContract.CommonDataKinds.Email.DATA;

    StringBuffer output = new StringBuffer();


    ContentResolver contentResolver = this.getContentResolver();

    Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
    // Loop for every contact in the phone
    if (cursor.getCount() > 0) 

        while (cursor.moveToNext()) 

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));

            if (hasPhoneNumber > 0) 
                String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
                // Query and loop for every phone number of the contact
                Cursor pCur = contentResolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]contact_id, ContactsContract.CommonDataKinds.Phone.NUMBER);
                int flag = 0;
                assert pCur != null;
                while (pCur.moveToNext()) 
                    String mobileNum = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));

                    if (flag == 0) 
                        if(mobileNum!=null)
                        mnumList.add(mobileNum);
                     else if (flag == 1) 
                        if(mobileNum!=null)
                            hnumList.add(mobileNum);
                     else if (flag == 2) 
                        if(mobileNum!=null)
                            wnumList.add(mobileNum);
                    
                    flag++;
                
                if(flag==1)
                    hnumList.add("");
                    wnumList.add("");
                    Log.e("Set","Both added");
                
                if(flag==2)
                    wnumList.add("");
                    Log.e("Set","W added");
                
                pCur.close();


            
        
    
        cursor.close();

                String MIME = ContactsContract.Data.MIMETYPE + "=?";
                String[] params = new String[]ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE;
                final Cursor nameCur = contentResolver.query(
                        ContactsContract.Data.CONTENT_URI,
                        null,
                        MIME,
                        params,
                        ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);


                assert nameCur != null;
                int i = 0;
                while (nameCur.moveToNext())
                    String fname = "";
                    String lname = "";
                    fname = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                    lname = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));

                    Log.e("In While","All the time");

                    if(fname!=null)
                        fnameList.add(fname);
                        Log.e("Put","Value Fname "+fname);
                    if(lname!=null) 
                        lnameList.add(lname);
                        Log.e("Put","Value Lname "+lname);
                    
                    if(fname==null)
                        fnameList.add(" ");
                    
                    if(lname==null)
                        lnameList.add(" ");
                    
                    i++;
                
                nameCur.close();


        Cursor cursorB = contentResolver.query(CONTENT_URI, null, null, null, null);
        // Loop for every contact in the phone
        if (cursorB.getCount() > 0) 

            while (cursorB.moveToNext()) 
                // Query and loop for every email of the contact
                String[] paramEmail = new String[]ContactsContract.CommonDataKinds.Email.CONTENT_TYPE;
                Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", paramEmail, ContactsContract.CommonDataKinds.Email.DISPLAY_NAME);
                int j=0;
                while (emailCursor.moveToNext()) 

                    email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
                    mailList.add(email);
                    Log.e("Email",email);
                    j++;
                
                if(j==0)
                    mailList.add("");
                    Log.e("Email","Dummy Added");
                
                emailCursor.close();

                output.append("\n");
            
        cursorB.close();

        Cursor cursorD = contentResolver.query(CONTENT_URI, null, null, null, null);
        // Loop for every contact in the phone
        if (cursorD.getCount() > 0) 

            while (cursorD.moveToNext()) 

                String contact_id = cursorD.getString(cursorD.getColumnIndex(_ID));
                //for url

                String newNoteUrl = "";
                String whereName3 = ContactsContract.Data.MIMETYPE + " = ?";
                String[] whereNameParams3 = new String[]ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE;


                ContentResolver contentResolverUrl = this.getContentResolver();
                try 
                    Cursor cursorUrl = contentResolverUrl.query(ContactsContract.Data.CONTENT_URI, null, whereName3, new String[]contact_id, ContactsContract.CommonDataKinds.Website.URL);

                    while (cursorUrl.moveToNext()) 
                        newNoteUrl = cursorUrl.getString(cursorUrl.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
                        Log.e("URL",newNoteUrl);
                    
                    Log.e("URL","Not Getting");
                    output.append("\nurl " + newNoteUrl);
                    firstItem.setUrl(newNoteUrl);


                    cursorUrl.close();
                 catch (IllegalArgumentException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                
            cursorD.close();

    Log.e("#######","##########################");
    for(int m=0;m<fnameList.size();m++)

        Log.e("Contact Val ",fnameList.get(m)+" , "+lnameList.get(m)+" , "+mnumList.get(m)+" , "+hnumList.get(m)+" , "+wnumList.get(m)+" , "+mailList.get(m));
        ContactsDO item = new ContactsDO();
        item.setUserId(AWSMobileClient.defaultMobileClient().getIdentityManager().getCachedUserID());
        item.setFirstName(fnameList.get(m));
        item.setLastName(lnameList.get(m));
        item.setMobileNumber(mnumList.get(m));
        item.setHomeNumber(hnumList.get(m));
        item.setWorkNumber(wnumList.get(m));
        item.setEmail(mailList.get(m));
        try 
            //saving to the database
            dynamoDBMapper.save(item);

         catch (final AmazonClientException ex) 
            Log.e(TAG, "Failed saving item : " + ex.getMessage(), ex);
        
    

【讨论】:

以上是关于如何一次查询联系人的所有详细信息的主要内容,如果未能解决你的问题,请参考以下文章

访问 android 联系人所有详细信息的最佳方式

在单个查询中获取联系人的详细信息

只需一次调用 MailChimp API v3 即可获取所有 mailchimp 活动的详细信息

检索特定联系人的所有详细信息

Android:在 Contact Uri 列表中显示所有有电话号码的联系人详细信息

如何获取特定联系人的联系人姓名详细信息