Reputation: 626
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 };
String selecao = Contacts.HAS_PHONE_NUMBER + " = 1";
Cursor contatos = contexto.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, projecao, selecao, null, null);
And to get Phone Number:
Cursor phones = contexto.getContentResolver().query(
Phone.CONTENT_URI,
new String[] { Phone.NUMBER },
Phone.CONTACT_ID + " = ?",
new String[] { contatos.getString(contatos
.getColumnIndex(Contacts._ID)) }, null);
I want to maintain a database of all contacts with numbers.
What I'm to do for get SIM card Contacts too?
Thank you for your time.
Upvotes: 0
Views: 9798
Reputation: 28229
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:
class Contact {
Long id;
String name;
String lookupKey;
List<String> phones = new ArrayList<>();
public Contact(Long id, String name, String lookupKey, String number) {
this.id = id;
this.name = name;
this.lookupKey = lookupKey;
this.phones.add(number);
}
}
Map<Long, Contact> contacts = new HashMap<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);
String number = cur.getString(3)
if (!contacts.containsKey(id)) {
Contact newContact = new Contact(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
Upvotes: 0
Reputation: 8641
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.
Upvotes: 0