【问题标题】:How to read contacts on Android 2.0如何在 Android 2.0 上读取联系人
【发布时间】:2009-11-12 10:23:09
【问题描述】:

我正在使用 Android 2.0 并正在尝试接收所有联系人的列表。

由于 android.provider.Contacts.People 已被弃用,我必须使用 android.provider.ContactsContract,但我找不到合适的示例来说明如何使用它(例如:检索电话簿上所有联系人的列表)。

有人知道在哪里可以找到这样的例子吗?

【问题讨论】:

  • 我也很想知道这一点。我只能找到旧方法的示例。

标签: android contacts android-2.0-eclair


【解决方案1】:

首先,确保你已经添加了

<uses-permission android:name="android.permission.READ_CONTACTS"/>

到您的 AndroidManifest.xml 文件中,然后您可以像这样遍历您的手机联系人:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
while (cursor.moveToNext()) { 
   String contactId = cursor.getString(cursor.getColumnIndex( 
   ContactsContract.Contacts._ID)); 
   String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
   if (Boolean.parseBoolean(hasPhone)) { 
      // You know it has a number so now query it like this
      Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null); 
      while (phones.moveToNext()) { 
         String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));                 
      } 
      phones.close(); 
   }

   Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null); 
   while (emails.moveToNext()) { 
      // This would allow you get several email addresses 
      String emailAddress = emails.getString( 
      emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); 
   } 
   emails.close();
}
cursor.close(); 

此外,您可以循环访问您的联系人,然后像这样简单地获取姓名和电话号码:

Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

while(people.moveToNext()) {
   int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
   String contact = people.getString(nameFieldColumnIndex);
   int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
   String number = people.getString(numberFieldColumnIndex);
}

people.close();

此外,如果您需要从联系人那里获取备注等信息,则需要使用不同的 URI,如下所示(请随意使用此方法):

private String getNote(long contactId) { 
   String note = null; 
   String[] columns = new String[] { ContactsContract.CommonDataKinds.Note.NOTE }; 
   String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
   String[] whereParameters = new String[]{Long.toString(contactId), ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}; 
   Cursor contacts = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, where, whereParameters, null); 
   if (contacts.moveToFirst()) { 
      rv = contacts.getString(0); 
   } 
   contacts.close(); 
   return note; 
} 

请注意,这次我不仅使用了联系人 ID,还使用了 mime 类型进行查询。

【讨论】:

  • 那是完美的哈维尔,感谢这一点,我不得不根据我的目的对其进行一些调整(检查是否有联系人以避免再次添加)。如果您想将其添加到您的帖子中,这是我的代码: String[] contactNameColumn = { ContactsContract.Contacts.DISPLAY_NAME };光标 checkContactInDatabase = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, contactNameColumn, ContactsContract.Contacts.DISPLAY_NAME + "=" + "'" + name + "'", null, null); if (checkContactInDatabase.moveToFirst()) { int nameFieldColumnIndex = checkContactInDatabase.getColumnIndex(PhoneLookup.DISPLAY_NAME);
  • 字符串联系人 = checkContactInDatabase.getString(nameFieldColumnIndex); Toast.makeText(Contact.this, contact + " " + getString(R.string.alreadySaved), Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT); i.setType(Contacts.CONTENT_ITEM_TYPE); i.putExtra(Insert.NAME, name); i.putExtra(插入。电话,电话); i.putExtra(插入.公司,公司); i.putExtra(插入。邮政,地址);开始活动(一); } checkContactInDatabase.close();
  • 嗨,我总是在这个陈述中得到错误 if (Boolean.parseBoolean(hasPhone));即使 hasPhone 的 value = "1"
  • 而不是 emails.getColumnIndex(ContactsContract.CommonDataKinds.CommonDataColumns.DATA));你也可以使用 emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
  • 您如何获得联系人照片?我在 SO 上看到了很多所谓的解决方案,但它们在很大程度上是不可靠的......
【解决方案2】:

很高兴看到一些有用的信息,令人沮丧的是,文档等对这个重要主题的涵盖程度如此之低。经过太多的黑客攻击后,我想我也会分享一些代码。下面的代码更漂亮一些,并且可以更有效地完成相同的事情。

Uri contactUri = ContactsContract.Contacts.CONTENT_URI;

    String[] PROJECTION = new String[] {

            ContactsContract.Contacts._ID,

            ContactsContract.Contacts.DISPLAY_NAME,

            ContactsContract.Contacts.HAS_PHONE_NUMBER,

    };

String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";

Cursor contacts = managedQuery(contactUri, PROJECTION, SELECTION, null, null );

上面的代码块返回一个指向结果查询的光标,该查询只包含那些具有电话号码的行。这很好,因为您通常有很多没有号码的联系人。此外,PROJECTION 限制了返回的数据量。

String key, value, phoneNumber; 

Hashtable contactPhoneInfo = new Hashtable<String, String>();

Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 

String [] PHONES_PROJECTION = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };

String PHONE_SELECTION = null; 

        contacts.moveToFirst();

        do{

         long contactId = contacts.getLong(idColumnIndex); 

         PHONE_SELECTION = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId; 

         Cursor phones = managedQuery(phoneUri,
           PHONES_PROJECTION,
           null, 
           null,
                    ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC");


         phones.moveToFirst(); 

         key = phones.getString(0).replaceAll("\\D", "");

         value = contacts.getString(nameColumnIndex); 

         contactPhoneInfo.put(key, value); 

        }while(contacts.moveToNext()); 

        contacts.close(); 
}

上述块获取与每个具有电话号码的联系人 ID 相关联的电话号码。我将所有信息存储在哈希表中,并带有电话号码的键值。我还删除了所有无数字信息的电话号码。出于某种原因,即使 ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER 是有效的,如果你在投影参数中包含它会破坏查询,我不知道为什么而且它确实令人沮丧。

上面代码的第二部分太慢了,所有的查询调用都把一切都搞砸了。下面的代码要快得多。只需获取电话内容的所有行并使用contact_ids 对您想要的数据进行排序。

Cursor phones = managedQuery(phoneUri,
                PHONES_PROJECTION,
                PHONE_SELECTION, 
                null,
                ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC");

contacts.moveToFirst();

        do{

            value = ""; 

            key = contacts.getString(idColumnIndex); 

            contactPhoneInfo.put(key, value);

        }while(contacts.moveToNext());

phones.moveToFirst();

        Set keySet = contactPhoneInfo.keySet(); 

        idColumnIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);

        int numColumnIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); 

        do{

            key = phones.getString(idColumnIndex);  

            if(keySet.contains(key)){

                value = phones.getString(numColumnIndex).replaceAll("\\D", ""); 

                contactPhoneInfo.put(key, value); 

            }


        }while(phones.moveToNext()); 

您最终会得到一个哈希表,其中包含您想要的所有信息。当然,您可以将任何您想要的信息放入数据结构中。第二种方法要快得多。

【讨论】:

  • 如果您只需要一些关联联系人的信息,您也可以在投影中使用隐式连接列(如ContactsContract.Data.DISPLAY_NAME);那么你就不必在 Java 中做一个凌乱的模拟连接了。
【解决方案3】:

只是想补充一下,当您检索联系人时,您可能会收到很多“垃圾”联系人 - 例如,用户在某些时候向某些电子邮件地址发送电子邮件,但未汇总...如果您只希望用户可以看到联系人,因为在 Android 自己的联系人应用程序中,您需要将选择限制为仅 IN_VISIBLE_GROUP。

    String where = ContactsContract.Contacts.IN_VISIBLE_GROUP + "= ? ";
    String[] selectionArgs = new String[] { "1" };

【讨论】:

    【解决方案4】:

    我认为在 StackOverflow 上有来自这个 URL http://coderzheaven.com/2011/06/get-all-details-from-contacts-in-android/ 的代码很重要,因为有时这样的链接会断开。

     public void readContacts(){
             ContentResolver cr = getContentResolver();
             Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                    null, null, null, 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));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        System.out.println("name : " + name + ", ID : " + id);
    
                        // get the phone number
                        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                                               ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                                               new String[]{id}, null);
                        while (pCur.moveToNext()) {
                              String phone = pCur.getString(
                                     pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                              System.out.println("phone" + phone);
                        }
                        pCur.close();
    
                        // get email and type
    
                       Cursor emailCur = cr.query(
                                ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                                new String[]{id}, null);
                        while (emailCur.moveToNext()) {
                            // This would allow you get several email addresses
                                // if the email addresses were stored in an array
                            String email = emailCur.getString(
                                          emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                            String emailType = emailCur.getString(
                                          emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
    
                          System.out.println("Email " + email + " Email Type : " + emailType);
                        }
                        emailCur.close();
    
                        // Get note.......
                        String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
                        String[] noteWhereParams = new String[]{id,
                        ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
                                Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
                        if (noteCur.moveToFirst()) {
                            String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                          System.out.println("Note " + note);
                        }
                        noteCur.close();
    
                        //Get Postal Address....
    
                        String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
                        String[] addrWhereParams = new String[]{id,
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
    //               Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
    //                       null, null, null, null);
                   Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
                           null, addrWhere, addrWhereParams, null);
    
                        while(addrCur.moveToNext()) {
                            String poBox = addrCur.getString(
                                         addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                            String street = addrCur.getString(
                                         addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                            String city = addrCur.getString(
                                         addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                            String state = addrCur.getString(
                                         addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                            String postalCode = addrCur.getString(
                                         addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                            String country = addrCur.getString(
                                         addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                            String type = addrCur.getString(
                                         addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
    
                            // Do something with these....
    
                        }
                        addrCur.close();
    
                        // Get Instant Messenger.........
                        String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
                        String[] imWhereParams = new String[]{id,
                            ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
                        Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
                                null, imWhere, imWhereParams, null);
                        if (imCur.moveToFirst()) {
                            String imName = imCur.getString(
                                     imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
                            String imType;
                            imType = imCur.getString(
                                     imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
                        }
                        imCur.close();
    
                        // Get Organizations.........
    
                        String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
                        String[] orgWhereParams = new String[]{id,
                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
                        Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
                                    null, orgWhere, orgWhereParams, null);
                        if (orgCur.moveToFirst()) {
                            String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                            String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                        }
                        orgCur.close();
                    }
                }
           }
        }
    

    强调文字

    【讨论】:

    【解决方案5】:

    我找到了读取联系人的非常简单的解决方案。 (编写读取每个值的代码很无聊,所以最好使用联系人的包装类)

    当然&lt;uses-permission android:name="android.permission.READ_CONTACTS"/&gt;

    ContactList.java

    package com.test;
    
    import java.util.ArrayList;
    
    public class ContactList {
    private ArrayList<Contact> contacts = new ArrayList<Contact>();
    
    public ArrayList<Contact> getContacts() {
        return contacts;
    }
    
    public void setContacts(ArrayList<Contact> contacts) {
        this.contacts = contacts;
    }
    
    public void addContact(Contact contact) {
         this.contacts.add(contact);
     }
    
     public ContactList() {
    
     }
    }
    

    Contact.java

    package com.test;
    
    import java.util.ArrayList;
    
    
    public class Contact {
    private String id;
     private String displayName;
     private ArrayList<Phone> phone;
     private ArrayList<Email> email;
     private ArrayList<String> notes;
     private ArrayList<Address> addresses = new ArrayList<Address>();
     private ArrayList<IM> imAddresses;
     private Organization organization;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getDisplayName() {
        return displayName;
    }
    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }
    public ArrayList<Phone> getPhone() {
        return phone;
    }
    public void setPhone(ArrayList<Phone> phone) {
        this.phone = phone;
    }
    public void addPhone(Phone phone) {
         this.phone.add(phone);
     }
    public ArrayList<Email> getEmail() {
        return email;
    }
    public void setEmail(ArrayList<Email> email) {
        this.email = email;
    }
    public void addEmail(Email email) {
         this.email.add(email);
     }
    public ArrayList<String> getNotes() {
        return notes;
    }
    public void setNotes(ArrayList<String> notes) {
        this.notes = notes;
    }
    public void AddNotes(String notes){
        this.notes.add(notes);
    }
    public ArrayList<Address> getAddresses() {
        return addresses;
    }
    public void setAddresses(ArrayList<Address> addresses) {
        this.addresses = addresses;
    }
    public void addAddress(Address address) {
         this.addresses.add(address);
     }
    public ArrayList<IM> getImAddresses() {
        return imAddresses;
    }
    public void setImAddresses(ArrayList<IM> imAddresses) {
        this.imAddresses = imAddresses;
    }
    public void addImAddresses(IM imAddr) {
         this.imAddresses.add(imAddr);
     }
    public Organization getOrganization() {
        return organization;
    }
    public void setOrganization(Organization organization) {
        this.organization = organization;
    }
    }
    

    地址.java

    package com.test;
    
    public class Address {
    private String poBox;
     private String street;
     private String city;
     private String state;
     private String postalCode;
     private String country;
     private String type;
     private String asString = "";
    
     public String getType() {
         return type;
     }
     public void setType(String type) {
         this.type = type;
     }
     public String getPoBox() {
         return poBox;
     }
     public void setPoBox(String poBox) {
         this.poBox = poBox;
     }
     public String getStreet() {
         return street;
     }
     public void setStreet(String street) {
         this.street = street;
     }
     public String getCity() {
         return city;
     }
     public void setCity(String city) {
         this.city = city;
     }
     public String getState() {
         return state;
     }
     public void setState(String state) {
         this.state = state;
     }
     public String getPostalCode() {
         return postalCode;
     }
     public void setPostalCode(String postalCode) {
         this.postalCode = postalCode;
     }
     public String getCountry() {
         return country;
     }
     public void setCountry(String country) {
         this.country = country;
     }
     public String toString() {
         if (this.asString.length() > 0) {
             return(this.asString);
         } else {
             String addr = "";
             if (this.getPoBox() != null) {
                 addr = addr + this.getPoBox() + "n";
             }
             if (this.getStreet() != null) {
                 addr = addr + this.getStreet() + "n";
             }
             if (this.getCity() != null) {
                 addr = addr + this.getCity() + ", ";
             }
             if (this.getState() != null) {
                 addr = addr + this.getState() + " ";
             }
             if (this.getPostalCode() != null) {
                 addr = addr + this.getPostalCode() + " ";
             }
             if (this.getCountry() != null) {
                 addr = addr + this.getCountry();
             }
             return(addr);
         }
     }
    
     public Address(String asString, String type) {
         this.asString = asString;
         this.type = type;
     }
    
     public Address(String poBox, String street, String city, String state, 
             String postal, String country, String type) {
         this.setPoBox(poBox);
          this.setStreet(street);
         this.setCity(city);
         this.setState(state);
         this.setPostalCode(postal);
         this.setCountry(country);
         this.setType(type);
     }
    }
    

    电子邮件.java

    package com.test;
    
    public class Email {
    private String address;
     private String type;
     public String getAddress() {
         return address;
     }
     public void setAddress(String address) {
         this.address = address;
     }
     public String getType() {
         return type;
     }
     public void setType(String t) {
         this.type = t;
     }
    
     public Email(String a, String t) {
         this.address = a;
         this.type = t;
     }
    }
    

    Im.java

    package com.test;
    
    public class IM {
    private String name;
     private String type;
     public String getName() {
         return name;
     }
     public void setName(String name) {
         this.name = name;
     }
     public String getType() {
         return type;
     }
     public void setType(String type) {
         this.type = type;
     }
    
     public IM(String name, String type) {
         this.name = name;
         this.type = type;
     }
    }
    

    组织.java

    package com.test;
    
    public class Organization {
    private String organization = "";
     private String title = "";
     public String getOrganization() {
         return organization;
     }
     public void setOrganization(String organization) {
         this.organization = organization;
     }
     public String getTitle() {
         return title;
     }
     public void setTitle(String title) {
         this.title = title;
     }
    
     public Organization() {
    
     }
     public Organization(String org, String title) {
         this.organization = org;
         this.title = title;
     }
    }
    

    电话.java

    package com.test;
    
    public class Phone {
    private String number;
     private String type;
    
     public String getNumber() {
         return number;
     }
    
     public void setNumber(String number) {
         this.number = number;
     }
    
     public String getType() {
         return type;
     }
    
     public void setType(String type) {
         this.type = type;
     }
    
     public Phone(String n, String t) {
         this.number = n;
         this.type = t;
     }
    }
    

    ContactAPI.java

    package com.test;
    
    import android.content.ContentResolver;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Build;
    
    public abstract class ContactAPI {
    private static ContactAPI api;
    
     public static ContactAPI getAPI() {
         if (api == null) {
             String apiClass;
             if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.ECLAIR) {
                 apiClass = "com.*********.ContactAPISdk5";
             } else {
                 apiClass = "com.*********.ContactAPISdk3";
             }
    
             try {
                 Class<? extends ContactAPI> realClass = Class.forName(apiClass).
                     asSubclass(ContactAPI.class);
                 api = realClass.newInstance();
             } catch (Exception e) {
                 throw new IllegalStateException(e);
             }
    
         }
         return api;
     }
    
     public abstract Intent getContactIntent();
    
     public abstract ContactList newContactList();
    
     public abstract Cursor getCur();
     public abstract void setCur(Cursor cur);
    
     public abstract ContentResolver getCr();
     public abstract void setCr(ContentResolver cr);
    
    }
    

    ContactAPISdk5.java

    package com.test;
    import java.util.ArrayList;
    import android.content.ContentResolver;
    import android.content.Intent;
    import android.database.Cursor;
    import android.provider.ContactsContract;
    
    public class ContactAPISdk5 extends ContactAPI {
    
     private Cursor cur;
     private ContentResolver cr;
    
    
     public Cursor getCur() {
         return cur;
     }
    
     public void setCur(Cursor cur) {
         this.cur = cur;
     }
    
     public ContentResolver getCr() {
         return cr;
     }
    
     public void setCr(ContentResolver cr) {
         this.cr = cr;
     }
    
     public Intent getContactIntent() {
         return(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI));
     }
    
     public ContactList newContactList() {
         ContactList contacts = new ContactList();
         String id;
    
         this.cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI,
                 null, null, null, null);
         if (this.cur.getCount() > 0) {
             while (cur.moveToNext()) {
                 Contact c = new Contact();
                 id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                 c.setId(id);
                 c.setDisplayName(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
                 if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                     c.setPhone(this.getPhoneNumbers(id));
                 }
                 c.setEmail(this.getEmailAddresses(id));
                 c.setNotes(this.getContactNotes(id));
                 c.setAddresses(this.getContactAddresses(id));
                 c.setImAddresses(this.getIM(id));
                 c.setOrganization(this.getContactOrg(id));
                 contacts.addContact(c);
             }
         }
         return(contacts);
     }
    
     public ArrayList<Phone> getPhoneNumbers(String id) {
         ArrayList<Phone> phones = new ArrayList<Phone>();
    
         Cursor pCur = this.cr.query(
                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                 null, 
                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                 new String[]{id}, null);
         while (pCur.moveToNext()) {
             phones.add(new Phone(
                     pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                     , pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))
             ));
    
         } 
         pCur.close();
         return(phones);
     }
    
     public ArrayList<Email> getEmailAddresses(String id) {
         ArrayList<Email> emails = new ArrayList<Email>();
    
         Cursor emailCur = this.cr.query( 
                 ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
                 null,
                 ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
                 new String[]{id}, null); 
         while (emailCur.moveToNext()) { 
             // This would allow you get several email addresses
             Email e = new Email(emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))
                     ,emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE))  
                     );
             emails.add(e);
         } 
         emailCur.close();
         return(emails);
     }
    
     public ArrayList<String> getContactNotes(String id) {
         ArrayList<String> notes = new ArrayList<String>();
         String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
         String[] whereParameters = new String[]{id, 
             ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}; 
         Cursor noteCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null); 
         if (noteCur.moveToFirst()) { 
             String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
             if (note.length() > 0) {
                 notes.add(note);
             }
         } 
         noteCur.close();
         return(notes);
     }
    
     public ArrayList<Address> getContactAddresses(String id) {
         ArrayList<Address> addrList = new ArrayList<Address>();
    
         String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
         String[] whereParameters = new String[]{id, 
                 ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE}; 
    
         Cursor addrCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null); 
         while(addrCur.moveToNext()) {
             String poBox = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
             String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
             String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
             String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
             String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
             String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
             String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
             Address a = new Address(poBox, street, city, state, postalCode, country, type);
             addrList.add(a);
         } 
         addrCur.close();
         return(addrList);
     }
    
     public ArrayList<IM> getIM(String id) {
         ArrayList<IM> imList = new ArrayList<IM>();
         String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
         String[] whereParameters = new String[]{id, 
                 ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE}; 
    
         Cursor imCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null); 
         if (imCur.moveToFirst()) { 
             String imName = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
             String imType;
             imType = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
             if (imName.length() > 0) {
                 IM im = new IM(imName, imType);
                 imList.add(im);
             }
         } 
         imCur.close();
         return(imList);
     }
    
     public Organization getContactOrg(String id) {
         Organization org = new Organization();
         String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
         String[] whereParameters = new String[]{id, 
                 ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE}; 
    
         Cursor orgCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
    
         if (orgCur.moveToFirst()) { 
             String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
             String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
             if (orgName.length() > 0) {
                 org.setOrganization(orgName);
                 org.setTitle(title);
             }
         } 
         orgCur.close();
         return(org);
     }
    
     }
    

    ContactAPISdk3.java

    package com.test;
    
    import java.util.ArrayList;
    
    import android.content.ContentResolver;
    import android.content.Intent;
    import android.database.Cursor;
    import android.provider.Contacts;
    import android.provider.Contacts.People;
    
    public class ContactAPISdk3 extends ContactAPI {
    
     private Cursor cur;
     private ContentResolver cr;
    
     public Cursor getCur() {
         return cur;
     }
    
     public void setCur(Cursor cur) {
         this.cur = cur;
     }
    
     public ContentResolver getCr() {
         return cr;
     }
    
     public void setCr(ContentResolver cr) {
         this.cr = cr;
     }
    
     public Intent getContactIntent() {
         return(new Intent(Intent.ACTION_PICK, People.CONTENT_URI));
     }
    
     public ContactList newContactList() {
         ContactList contacts = new ContactList();
         String id="";
    
         this.cur = this.cr.query(People.CONTENT_URI, 
                 null, null, null, null);
         if (this.cur.getCount() > 0) {
             while (cur.moveToNext()) {
                 Contact c = new Contact();
                 id = cur.getString(cur.getColumnIndex(People._ID));
                 c.setId(id);
                 c.setDisplayName(cur.getString(cur.getColumnIndex(People.DISPLAY_NAME)));
                 if (Integer.parseInt(cur.getString(cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
                     c.setPhone(this.getPhoneNumbers(id));
                 }
                 c.setEmail(this.getEmailAddresses(id));
                 ArrayList<String> notes = new ArrayList<String>();
                 notes.add(cur.getString(cur.getColumnIndex(People.NOTES)));
                 c.setNotes(notes);
                 c.setAddresses(this.getContactAddresses(id));
                 c.setImAddresses(this.getIM(id));
                 c.setOrganization(this.getContactOrg(id));
                 contacts.addContact(c);
             }
         }
         return(contacts);
     }
    
     public ArrayList<Phone> getPhoneNumbers(String id) {
         ArrayList<Phone> phones = new ArrayList<Phone>();
    
         Cursor pCur = this.cr.query(
                 Contacts.Phones.CONTENT_URI, 
                 null, 
                 Contacts.Phones.PERSON_ID +" = ?", 
                 new String[]{id}, null);
         while (pCur.moveToNext()) {
             phones.add(new Phone(
                     pCur.getString(pCur.getColumnIndex(Contacts.Phones.NUMBER))
                     , pCur.getString(pCur.getColumnIndex(Contacts.Phones.TYPE))
             ));
    
         } 
         pCur.close();
         return(phones);
     }
    
     public ArrayList<Email> getEmailAddresses(String id) {
         ArrayList<Email> emails = new ArrayList<Email>();
    
         Cursor emailCur = this.cr.query( 
                 Contacts.ContactMethods.CONTENT_EMAIL_URI, 
                 null,
                 Contacts.ContactMethods.PERSON_ID + " = ?", 
                 new String[]{id}, null); 
         while (emailCur.moveToNext()) { 
             // This would allow you get several email addresses
             Email e = new Email(emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMethods.DATA))
                     ,emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMethods.CONTENT_EMAIL_TYPE))  
                     );
             emails.add(e);
         } 
         emailCur.close();
         return(emails);
     }
    
     public ArrayList<Address> getContactAddresses(String id) {
         ArrayList<Address> addrList = new ArrayList<Address>();
    
         String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?"; 
         String[] whereParameters = new String[]{id, 
                 Contacts.ContactMethods.CONTENT_POSTAL_ITEM_TYPE}; 
    
         Cursor addrCur = this.cr.query(Contacts.ContactMethods.CONTENT_URI, null, where, whereParameters, null); 
         while(addrCur.moveToNext()) {
             String addr = addrCur.getString(addrCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
             String type = addrCur.getString(addrCur.getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
             Address a = new Address(addr, type);
             addrList.add(a);
         } 
         addrCur.close();
         return(addrList);
     }
    
     public ArrayList<IM> getIM(String id) {
         ArrayList<IM> imList = new ArrayList<IM>();
         String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?"; 
         String[] whereParameters = new String[]{id, 
                 Contacts.ContactMethods.CONTENT_IM_ITEM_TYPE}; 
    
         Cursor imCur = this.cr.query(Contacts.ContactMethods.CONTENT_URI, null, where, whereParameters, null); 
         if (imCur.moveToFirst()) { 
             String imName = imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
             String imType = imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
             if (imName.length() > 0) {
                 IM im = new IM(imName, imType);
                 imList.add(im);
             }
         } 
         imCur.close();
         return(imList);
     }
    
     public Organization getContactOrg(String id) {
         Organization org = new Organization();
         String where = Contacts.ContactMethods.PERSON_ID + " = ?"; 
         String[] whereParameters = new String[]{id}; 
    
         Cursor orgCur = this.cr.query(Contacts.Organizations.CONTENT_URI, null, where, whereParameters, null);
    
         if (orgCur.moveToFirst()) { 
             String orgName = orgCur.getString(orgCur.getColumnIndex(Contacts.Organizations.COMPANY));
             String title = orgCur.getString(orgCur.getColumnIndex(Contacts.Organizations.TITLE));
             if (orgName.length() > 0) {
                 org.setOrganization(orgName);
                 org.setTitle(title);
             }
         } 
         orgCur.close();
         return(org);
     }
     }
    

    注意:不要忘记更改包名而不是*******

    Source(链接随时可能失效:))

    【讨论】:

      【解决方案6】:

      放这个....

      Cursor phones = 
      
          getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
                      while (phones.moveToNext())
                      {
                      String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                      String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
      }
      

      如果有任何问题,请告诉我。

      【讨论】:

        【解决方案7】:

        这部分不适合我:

         while (phones.moveToNext()) { 
             String phoneNumber = phones.getString( 
               phones.getColumnIndex( 
                 ContactsContract.CommonDataKinds.Phone.NUMBER));                 
            } 
        

        如果我使用它,它确实可以:

         while (phones.moveToNext()) { 
                                          String pdata = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
                                          Log.v("DATA",pdata);
        }
        

        【讨论】:

          【解决方案8】:

          您可以使用 android 开发者网站上的“ContactManager”示例 (要么) 转到您设置路径以在系统中下载 android-sdk 的位置。在 android-sdk-mac_x86/samples/android-10 文件夹中,您可以看到“ContactManager”示例。

          我已尝试使用此示例,在我的应用程序中运行良好。

          【讨论】:

            【解决方案9】:

            我使用的是三星 Galaxy Note 4,但我不知道为什么以上方法都不适合我。 我混合了一些,让这个 woking..

                Cursor people = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                people.moveToFirst();
                while(people.moveToNext()) {
                   int nameFieldColumnIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                   String contact = people.getString(nameFieldColumnIndex);
                   int numberFieldColumnIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
                   String number = people.getString(numberFieldColumnIndex);
                   dbWriter.execSQL("Insert Into ContactsList (ContactName, ContactNumber) Values (" +
                             "'" + contact.replace("'",  "''") + "', '" + number.replace("'",  "''") + "')");
                }
                people.close();
            

            【讨论】:

              猜你喜欢
              • 2011-07-20
              • 2023-03-08
              • 1970-01-01
              • 1970-01-01
              • 2011-01-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多