I'm getting all the contacts from the local address book, together with their names + phone numbers but the problem is it's return e-mail addresses that I exchanged mails with and also Skype ID's, things I don't need :)
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.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 = 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()) {
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n Name:" + name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
}
output.append("\n");
}
outputText.setText(output);
}
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Your problem is not Android-related, but rather a Java issue.
In your largest while loop make sure a continue keyword in the hasPhoneNumber IF, or just move the output.append("\n") into the IF.
Cheers. :-)
Related
I am getting only name & birthday using the code below. But I need phone number & email also. It would be great if anyone can help me out. Thanks.
private void getContacts() {
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Event.START_DATE
};
String where = ContactsContract.Data.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
};
String sortOrder = null;
ContentResolver contentResolver = this.getActivity().getContentResolver();
Cursor cursor = contentResolver.query(uri, projection, where, selectionArgs, sortOrder);
int nameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int emailColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
int bithDayColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
while (cursor.moveToNext()) {
String name = cursor.getString(nameColumn);
String number = cursor.getString(numberColumn);
String email = cursor.getString(emailColumn);
String birthDay = cursor.getString(bithDayColumn);
Log.d(TAG, "Birthday: " + birthDay);
}
}
In your projection you're limiting your query to rows of MIMETYPE CommonDataKinds.Event.CONTENT_ITEM_TYPE only, so you'll only get birthdays.
You need to ask for emails and phones mimetypes, but note that these additional information will come in separate rows for the same contact.
For example, for contact A that has 2 phones, 3 emails and a birthday, you'll get 6 results in your cursor. So you need to group them all together using the CONTACT_ID field.
Here's simple code to get you started, print the resulting HashMap and you'll get for each contact all his/hers name, emails, phones and birthday:
Map<Long, List<String>> contacts = new HashMap<Long, List<String>>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
// query only emails/phones/events
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Event.CONTENT_ITEM_TYPE"', '" + Email.CONTENT_ITEM_TYPE + "')";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String mime = cur.getString(2); // type of data (phone / birthday / email)
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
String kind = "unknown";
switch (mime) {
case Phone.CONTENT_ITEM_TYPE:
kind = "phone";
break;
case Event.CONTENT_ITEM_TYPE:
kind = "birthday";
break;
case Email.CONTENT_ITEM_TYPE:
kind = "email";
break;
}
Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data);
// add info to existing list if this contact-id was already found, or create a new list in case it's new
List<String> infos;
if (contacts.containsKey(id)) {
infos = contacts.get(id);
} else {
infos = new ArrayList<String>();
infos.add("name = " + name);
contacts.put(id, infos);
}
infos.add(kind + " = " + data);
}
how to get email address from contact list.below code I got number and name and display on list.but I want number,name and email address so pls check below code
ContentResolver contactResolver = context.getContentResolver();
Cursor c = contactResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER }, null, null, null);
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
if(cursor.getCount()>0)
while ( cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.e("TAG", " Name: " + displayName+"==>phone Number==>"+number);
contactNameArrayList.add(displayName);
contactNumberArrayList.add(number);
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
// Log.e("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
null, null, null);
while (emailCursor.moveToNext())
{
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.e("TAG", s + " email: " + email);
}
emailCursor.close();
} cursor.close();
Log.e(TAG,"contactNameArrayList sIZE==>"+contactNameArrayList.size()+"contactNumberArrayList size==>"+contactNumberArrayList.size()+"contactEmailAddressArrayList size==>"+contactEmailAddressArrayList.size());
}
I create three array for name and number and email id but above code I got only mobile and name.when I am add name and mobile no in array so simultaneously store email id particular mobile no in email id array.so pls help ...
You can get Email from contact using this
public List<String> getEmail(int contactId) {
List<String> emailStr = new ArrayList<String>();
ContentResolver cr = context.getContentResolver();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{String.valueOf(contactId)}, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailStr.add(email);
System.out.println("Email " + email );
}
emailCur.close();
return emailStr;
}
Use Following Code to get multiple numbers and email from one contact and all contacts from phonebook.
private void getContactsFromPhoneBook() {
String unique_id = ApplicationConstant.phone_id;
System.out.println("Unique_ID : " + unique_id);
Contact_To_Sync contact_to_sync = new Contact_To_Sync();
List<Contacts> AllContact_toSync = new ArrayList<>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
System.out.println("Contacts Count : " + cur.getCount());
if (cur.getCount() > 0) {
Contacts contacts = null;
List<String> Phones;
List<String> Emails;
while (cur.moveToNext()) {
contacts = new Contacts();
Phones = new ArrayList<>();
Emails = new ArrayList<>();
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String timeStamp = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP));
contacts.setContact_id(id);
contacts.setName(name);
System.out.println("name : " + name + ", ID : " + id + " Status : " + timeStamp);
// 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);
Phones.add(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));
Emails.add(email);
System.out.println("Email " + email + " Email Type : " + emailType);
}
emailCur.close();
contacts.setEmails(Emails);
contacts.setPhones(Phones);
AllContact_toSync.add(contacts);
}
contact_to_sync.setContacts(AllContact_toSync);
contact_to_sync.setPhone_device_name(unique_id);
if (!contact_to_sync.getContacts().isEmpty()) {
Sync_Contacts_To_Server(contact_to_sync);
}
}
}
I am using Contact picker library for selecting multiple contacts but if a contact doesn't contain any number and if it is selected then it is showing some null pointer exception in the edit text field. How to remove that message and also how to remove trailing comma. Below is my Code.
try {
int pos = 0;
for (Contact contact : contacts) {
String displayName = contact.getDisplayName();
result.append(displayName + ",");
result.setSpan(new BulletSpan(15), pos, pos + displayName.length() + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//pos += displayName.length() + 1;
}
}
catch (Exception e) {
result.append(e.getMessage());
}
contactsView.setText(result);
please try to check this code
void getAllContacts() {
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> numberList = new ArrayList<>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER;
String[] list = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.Contacts._ID};
Cursor cursor = getContentResolver().query(uri, list, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
String contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contactNuber.add(contactNumber);
contactsName.add(contactName);
nameList.add(contactName);
numberList.add(contactNumber);
} while (cursor.moveToNext());
cursor.close();
myContacts.put("name", nameList);
myContacts.put("number", numberList);
}
}
I'm looking to export the contacts that are stored in the native database.
I'm having trouble retrieving contacts from native database.
Here is the query I would like to use :
Get all the contacts that have at least a phone number or an email.
Here is the query I am using :
String dataWhere = ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?";
String[] dataWhereValues = new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
String[] dataProjection = new String[]{ContactsContract.Data.CONTACT_ID, ContactsContract.Data.LOOKUP_KEY, ContactsContract.Data.DISPLAY_NAME_PRIMARY, ContactsContract.Data.STARRED, ContactsContract.Data.MIMETYPE, ContactsContract.Data.DATA1, ContactsContract.Data.DATA2, ContactsContract.Data.DATA_VERSION};
Cursor data = getContentResolver().query(ContactsContract.Data.CONTENT_URI, dataProjection, dataWhere, dataWhereValues, ContactsContract.Data.CONTACT_ID);
But this query gives me lots of weird contacts, and some of my contacts are also missing...
Can anyone help me please ?
this may help you for getting phone numbers and display names...
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
// importing phone contacts
while (phones.moveToNext())
{
listMobileNo.add(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
listName.add(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
}
phones.close();
Here is the query I ended up with
String where = ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?";
String[] whereValues = new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] dataProjection = new String[]{ContactsContract.Data.CONTACT_ID, ContactsContract.Data.LOOKUP_KEY, ContactsContract.Data.DISPLAY_NAME_PRIMARY, ContactsContract.Data.STARRED, ContactsContract.Data.MIMETYPE, ContactsContract.Data.DATA1, ContactsContract.Data.DATA2, ContactsContract.Data.DATA_VERSION};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, dataProjection, dataWhere, dataWhereValues, ContactsContract.Data.CONTACT_ID + " ASC");
int cidIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID);
int nameIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.DISPLAY_NAME_PRIMARY);
int starredIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.STARRED);
int typeIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE);
int data1Index = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA1);
int data2Index = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA2);
int lookupKeyIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.LOOKUP_KEY);
int versionIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA_VERSION);
boolean hasData = cursor.moveToNext();
while (hasData){
contactId = cursor.getLong(cidIndex);
nativeLookupKey = cursor.getString(lookupKeyIndex);
fullName = cursor.getString(nameIndex);
starred = cursor.getInt(starredIndex);
version = cursor.getLong(versionIndex);
while (currentContactId <= contactId && hasData) {
if (currentContactId == contactId) {
String type = cursor.getString(typeIndex);
if (type.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
String email = cursor.getString(data1Index);
} else if (type.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
String number = cursor.getString(data1Index);
}
}
hasData = cursor.moveToNext();
if (hasData) {
currentContactId = cursor.getLong(cidIndex);
}
}
}
Android contact - does each contact have a unquieid? How do I get the unquieid?
protected void getContactInfo(Intent intent)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
// Find Email Addresses
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
Cursor address = getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
null, null);
while (address.moveToNext())
{
// These are all private class variables, don't forget to create them.
poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
} //address.moveToNext()
} //while (cursor.moveToNext())
cursor.close();
}//getContactInfo