Skip to content Skip to sidebar Skip to footer

Android How To Read Android Contacts And Sim Contacts?

I am currently getting read only android contacts, below is the code I'm using: String[] projecao = new String[] { Contacts._ID, Contacts.LOOKUP_KEY, Contacts.DISPLAY_NAME }; S

Solution 1:

The Contacts you're reading are from the Contacts Provider, which is part of the Android platform. They're not read-only, although you should read the documentation before attempting to change them.

SIM card contacts are completely different. They're stored separately on the SIM card itself, and you probably have to use an app from the handset manufacturer or service provider to get to them. They have nothing to do with Google Contacts. I recommend against doing anything with them.

Solution 2:

First, running a phone-query for each contact is very inefficient and may cause your code to run a few minutes (!!) on devices with a lot of contacts.

Here's code that will get all the info you need with a single quick query:

classContact {
    Long id;
    String name;
    String lookupKey;
    List<String> phones = newArrayList<>();

    publicContact(Long id, String name, String lookupKey, Stringnumber) {
        this.id = id;
        this.name = name;
        this.lookupKey = lookupKey;
        this.phones.add(number);
    }
}

Map<Long, Contact> contacts = newHashMap<Long, PhoneContact>();

String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.LOOKUP_KEY, Phone.NUMBER};
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "')"; 

Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);

while (cur.moveToNext()) {
    long id = cur.getLong(0);
    String name = cur.getString(1);
    String lookup = cur.getString(2);
    Stringnumber = cur.getString(3)

    if (!contacts.containsKey(id)) {
        Contact newContact = newContact(id, name, lookup, number);
        contacts.put(id, phoneContact);
    } else {
        Contact existingContact = contacts.get(id);
        existingContact.phones.add(number);
    }
}
cur.close();

Regarding SIM contacts, they are already stored on the same database, and accessible via ContactsContract, which means all phones stored on the SIM should be also received with the above code.

If you want to query for SIM contacts ONLY see my answer here: https://stackoverflow.com/a/49624417/819355

Post a Comment for "Android How To Read Android Contacts And Sim Contacts?"