Store hidden sync identifier in android raw contact - android

I'd like to create an app which syncs contacts from a given server. To identify those contacts, I'd like to store a identifier in the android contact in a hidden field.
I've found the field SYNC1 which seems to appropriate for that, but I've no idea how to use this field correctly.
I tried setting it in the following way:
ArrayList<ContentProviderOperation> ops =
new ArrayList<>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, ACCOUNT_NAME)
.withValue(ContactsContract.RawContacts.SYNC1, "myInternalId")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Test User")
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
The issue is now, that the batch insert runs through, but the field isn't set in the contact, because it is empty when I try to read it afterwards:
ContentResolver cr = this.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));
String sync1 = null;
int sync1Index = cur.getColumnIndex(ContactsContract.RawContacts.SYNC1);
if (sync1Index >= 0) {
sync1 = cur.getString(sync1Index);
}
System.out.println("Contact id=" + id + " name=" + name + " sync1=" + sync1);
}
}
cur.close();
If I want to set it in the raw contact, so in the second batch, I get an exception.

The way you insert the value seems correct, but the method that reads the value isn't.
You can't query Contacts.CONTENT_URI and get fields from the RawContacts table.
To read back your value, try this:
ContentResolver cr = this.getContentResolver();
String[] projection = new String[] { RawContacts._ID, RawContacts.CONTACT_ID, RawContacts.SYNC1 }
String selection = RawContacts.ACCOUNT_TYPE + " = '" + accountType + "' AND " + RawContacts.ACCOUNT_NAME + " = '" + accountName + "'";
Cursor cur = cr.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, null, null);
while (cur.moveToNext()) {
Long rawId = cur.getLong(0);
Long contactId = cur.getLong(1);
String sync1 = cur.getString(2);
System.out.println("Contact id=" + contactId + " raw-id=" + rawId + " sync1=" + sync1);
}
cur.close();

Related

Select one contact number from a list of multiple contact numbers

I want to fetch only the first contact number from a list of contact numbers of a particular user, with the help of cursor. Here is my code:
private ArrayList<ArrayList<String>> getAllContacts() {
ArrayList<ArrayList<String>> nameList = new ArrayList<ArrayList<String>>();
ArrayList<String> person=new ArrayList<>();
ArrayList<String> number=new ArrayList<>();
ArrayList<String> temp=new ArrayList<>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur!=null ? cur.getCount() : 0) > 0) {
while (cur!=null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
person.add(name);
if (cur.getInt(cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
if(pCur.getCount()==1) {
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
number.add(phoneNo);
}
}
else{
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
temp.add(phoneNo);
}
number.add(temp.get(0));
temp.clear();
}
pCur.close();
}
}
}
if (cur!=null) {
cur.close();
}
Log.d("contacts",String.valueOf(number.size())+" "+String.valueOf(person.size())); //the lists aren't of equal size
if(person.size()==number.size()){
nameList.add(person);
nameList.add(number);
}
else{
//don't know what to do here
}
return nameList;
}
But, the code still fetches multiple contact numbers saved for a single user, in other words person.size() is not equal to number.size(). What do I do?
The array sizes are not the same because not all contacts have phone-numbers, you are correctly checking for HAS_PHONE_NUMBER and only if true, getting that contact's phone numbers - which means number.size() would be < person.size() on most phones.
I would suggest instead of keeping separate Arrays for names and phones, having a single Array with a simple java class that represents a person.
Other than that, your code is very inefficient, as you're doing a ton of queries, while you can do just one.
Here's an example with the two suggestions above:
class Person {
long id,
String name,
String firstPhone;
public Person(id, name, firstPhone) {
this.id = id;
this.name = name;
this.firstPhone = firstPhone;
}
}
Map<Long, Person> mapping = new HashMap<>(); // mapping between a contact-id to a Person object
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Phone.NUMBER};
// query phones only
String selection = Data.MIMETYPE + "='" + Phone.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 phone = cur.getString(2); // phone
Log.d(TAG, "got " + id + ", " + name + " - " + data);
// only add a new object if we haven't seen this person before
if (!mapping.containsKey(id)) {
Person person = new Person(id, name, phone);
mapping.put(id, person);
}
}
cur.close();
Array<Person> people = mapping.values();
EDIT
Set<Long> ids = new HashSet<Long>();
Array<String> names = new ArrayList<String>();
Array<String> numbers = new ArrayList<String>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Phone.NUMBER};
// query phones only
String selection = Data.MIMETYPE + "='" + Phone.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 phone = cur.getString(2); // phone
Log.d(TAG, "got " + id + ", " + name + " - " + data);
// only add a new object if we haven't seen this person before
if (ids.add(id)) {
names.add(name);
numbers.add(phone);
}
}
cur.close();

How to get email from contact

This code is working fine for fetching name and phone but i don't know how to get email from this code. Here is my code :
public static ArrayList<ContentValues> getContactDetails(final Context mContext){
ArrayList<ContentValues> contactList = new ArrayList<ContentValues>();
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor managedCursor = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, order);
int _number = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int _name = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int _id = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
while (managedCursor.moveToNext()) {
ContentValues values = new ContentValues();
Contact mContact = new Contact();
values.put(ContactClass.CONTACT_NAME, managedCursor.getString(_name));
values.put(ContactClass.CONTACT_MOBILE_NUMBER, managedCursor.getString(_number).replaceAll("\\s+",""));
mContact.setPhNo(managedCursor.getString(_number).replaceAll("\\s+",""));
mContact.setName(managedCursor.getString(_name));
contactList.add(values);
serverContactList.add(mContact);
}
}
return contactList;
}
here i want to get email and add to serverContactList list.
I edited your code, add rest of your code in 2 todos.
public static ArrayList<ContentValues> getContactDetails(final Context mContext) {
// todo rest of things
int _id = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
while (managedCursor.moveToNext()) {
// we will get emails for a contact id
String id = managedCursor.getString(_id);
Cursor cur1 = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
if (cur1 != null) {
while (cur1.moveToNext()) {
//to get the contact names
String name = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.e("Name :", name);
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email", email);
}
}
cur1.close();
// todo rest of things
}
return contactList;
}
Don't use managedCursor, ever.
Query over Data.CONTENT_URI instead of Phone.CONTENT_URI to get access to all Data items (including Phone and Email and others if needed)
Limit the query by MIMETYPE to just the items you need
Map<Long, Contact> contacts = new HashMap<>();
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 + "', '" + 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 / email)
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
Log.d(TAG, "got " + id + ", " + name + " - " + data);
// add info to existing list if this contact-id was already found, or create a new list in case it's new
Contact contact;
if (contacts.containsKey(id)) {
contact = contacts.get(id);
} else {
contact = new Contact();
contacts.put(id, contact);
contact.setName(name);
}
if (mime == Phone.CONTENT_ITEM_TYPE) {
contact.setPhNo(data);
} else {
contact.setEmail(data);
}
}

How to get non duplicated phone numbers from android contacts content provider

I am trying to get all contacts which have mobile numbers.
I am able to fetch the contacts.But the problem is it gives me duplicate contacts.same phone number comes two times.
I used the following code to get contacts.
public static List<RawContact> getAllContacts(Context context,Account account){
Log.d(TAG, "*** Looking for local contacts with mobile number!!");
String phoneNumber = null;
String email = null;
int numberOfContacts = 0;
List<RawContact> newContacts = new ArrayList<RawContact>();
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;
List<RawContact> localNewContacts = new ArrayList<RawContact>();
final ContentResolver contentResolver = context.getContentResolver();
final Cursor cursor = contentResolver.query(CONTENT_URI,
null,
null,
null,
null);
if(cursor.getCount()>0){
numberOfContacts = 0;
Log.d(TAG, "*** Looking for local contacts "+cursor.getCount());
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)));
final long rawContactId = cursor.getLong(DirtyQuery.COLUMN_RAW_CONTACT_ID);
if (hasPhoneNumber > 0) {
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' "+" AND "+ Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
Log.d(TAG,"Phone number is: "+phoneNumber);
RawContact rawContact = getRawContact(context, rawContactId);
Log.d(TAG, "Contact Name: " + rawContact.getBestName());
localNewContacts.add(rawContact);
}phoneCursor.close();
}
numberOfContacts++;
Log.d(TAG, "numberOfContacts updated: "+numberOfContacts);
}
}
return localNewContacts;
}
How to solve this issue
You're getting duplicate contacts because you're actually reading RawContacts, not contacts. Multiple RawContacts can and will contain info about a single person represented by a single Contact.
You need a single query over the Phones table, and organize the data using a HashMap from CONTACT_ID to Contact info, so you won't get duplicates.
The Contacts DB is organized in three main tables:
Contacts - each entry represents one contact, and groups together one or more RawContacts
RawContacts - each entry represents data about a contact that was synced in by some SyncAdapter (e.g. Whatsapp, Google, Facebook, Viber), this groups multiple Data entries
Data - The actual data about a contact, emails, phones, etc. each line is a single piece of data that belongs to a single RawContact
You're trying to make a query on the Contacts table, with projection of fields from the Data table, you can't do that.
You can use something like the following code, just convert the HashMap to work with your ContactModel object:
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 };
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "')";
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);
String mime = cur.getString(2); // type of data (e.g. "phone")
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
int type = cur.getInt(4); // a numeric value representing type: e.g. home / office / personal
String label = cur.getString(5); // a custom label in case type is "TYPE_CUSTOM"
String labelStr = Phone.getTypeLabel(getResources(), type, label);
Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data + " (" + labelStr + ")");
// 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 + " (" + labelStr + ")");
}
Here is quick solution i came up with
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC ");
contactArray = new ArrayList<>();
String tempId = "";
if(cursor != null && cursor.getCount() > 0){
while(cursor.moveToNext())
{
String contact_id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
if(!tempId.equals(contact_id)){
String contact_name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contact_number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String result = contact_id+"\n"+contact_name+"\n"+contact_number;
contactArray.add(result);
}
tempId = contact_id;
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contactArray);
listView.setAdapter(adapter);
cursor.close();

Selecting contacts from phone-book by mime type

I am trying to fetch contacts from phone by MIME-TYPE, so i can select contacts that has the type:
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
Here is the method i use:
public static ArrayList<Contact> fetchContactsFromPhone(#NonNull Context context) {
ArrayList<Contact> contacts = new ArrayList<>();
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;
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
long hasPhoneNumber = Long.parseLong(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI,
null,
Phone_CONTACT_ID + " = " + contact_id + " AND " + ContactsContract.Data.MIMETYPE + " = " + "'"+ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE+"'"
, null, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
Contact contact = new Contact();
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber = phoneNumber.replaceAll("[()\\-\\s]", "").trim();
contact.setName(name);
contact.setPhoneNum(phoneNumber);
contacts.add(contact);
}
phoneCursor.close();
}
}
}
cursor.close();
}
//return data
return contacts;
}
The problem is this query, return ZERO contacts.
Any Idea why?
You're querying the table CommonDataKinds.Phone.CONTENT_URI which contains only Data rows with MIMETYPE = CommonDataKinds.Phone.CONTENT_ITEM_TYPE.
But you're asking for rows with MIMETYPE CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE so you're getting an empty cursor.
It's an easy fix to your existing code, but even when fixed, you're code is very slow, it'll run a query per contact on the device, this can easily be hundreds or even thousands of queries. If you just need to get the name+number of all contacts, try the following code (one query to get all):
ArrayList<Contact> contacts = new ArrayList<>();
// Make sure you import Phone from ContactsContract.CommonDataKinds.Phone
String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor cur = cr.query(Phone.CONTENT_URI, projection, null, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1);
String number = cur.getString(2);
Log.d(TAG, "got " + id + ", " + name + ", " + number);
Contact contact = new Contact();
contact.setName(name);
contact.setPhoneNum(number);
contacts.add(contact);
}
if (cur != null) {
cur.close();
}
Note that similar to your code, this code might create multiple Contact objects for each contact, in case a contact has more then one phone.
If you want only one Contact object per contact, you need to modify your Contact object to contain a list of phones, and change the ArrayList<Contact> to HashMap<Long, Contact> so you can add a phone to an existing object instead of creating a new one.

Android Contacts Content Provider sometimes returns empty phone numbers

Here is the code used to get the contact information :
String id = data.getData().getLastPathSegment();
Cursor cursor = getActivity().getContentResolver()
.query(ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.Data.DISPLAY_NAME},
ContactsContract.Data.CONTACT_ID + "=?",
new String[]{id},
null);
// short circuit if we didn't pick a contact
if (cursor.getCount() == 0) {
return;
}
String contact = "";
String contactName = "";
//code to get contact name
if (cursor.moveToFirst() && cursor.getString(0) != null) {
contact = contact + cursor.getString(0) + ",";
contactName = cursor.getString(0);
}
else {
contact = contact + ","; //changed
}
cursor.close();
// code to get phone number
cursor = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
newString[{ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
new String[]{id},null);
if (cursor.moveToFirst() && cursor.getString(0) != null) {
contact = contact + cursor.getString(0) + ",";
contact = contact + cursor.getString(0) + ",";
}
else {
contact = contact + ",,"; //changed
}
cursor.close();
//Code to get email
cursor = getActivity().getContentResolver()
.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Email.ADDRESS},
ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?",
new String[]{id},null);
if (cursor.moveToFirst() && cursor.getString(0) != null) {
contact = contact + cursor.getString(0);
}
cursor.close();
contact = contact.replace("+", "");
Log.i("TAG", "CONTACT INFO = " + contact);
What I am trying to do:
Here, I query the contact name, phone number and email from Contacts through content provider and concatenate all three into a single string, with commas separating them within the string .
The problem :
I get the contact name and email, without any issues.
However, when I select some contacts from contact, the phone number returned is empty.
The Contacts that return empty phone numbers are phone numbers from a different country, from my current location.
I am right now in Canada and when I select Canadian Contacts, I get the phone number correctly.
However, when I select phone numbers from India, the number is not returned, instead, I get empty result.
The same happens when I select a Contact with numbers like "12345" or "5555555555"etc.
My Question
Could it be that Android is trying to validate the authenticity of the number and returning an empty number, if it finds the phone number Invalid? *(probably not! Must be my mistake!)*
How can I solve this issue? Can't I get the value of the phone number just like how it is saved in the Contacts by the user?
I apologize for any unambiguity in the code or my question. I am a novice programmer and thanks a lot for all your inputs!
One thing i observed from that code is, you are reading contacts with out using
ContactsContract.Contacts.CONTENT_URI
I Modified your code and created a new method to print all contacts.
public static void fetchContacts(Context context) {
String phoneNumber = 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;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
long hasPhoneNumber = Long.parseLong(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
output.append("\n Name:" + name);
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 Number:" + phoneNumber);
System.out.println("Number:::::"+phoneNumber);
System.out.println("Contact:::::"+output.toString());
}
phoneCursor.close();
}
}
}else{
// Toast.makeText(context, "No contacts Found", Toast.LENGTH_LONG).show();
}
}

Categories

Resources