Retrieving contacts - android

I have tried to get phone number also but i didn't no how to get using this code . This the code i am using please tell how to get number by same code for same id
// method to get name, contact id, and birthday
private Cursor getContactsBirthdays() {
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
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;
return managedQuery(uri, projection, where, selectionArgs, sortOrder);
}
// iterate through all Contact's Birthdays and print in log
Cursor cursor = getContactsBirthdays();
int bDayColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
while (cursor.moveToNext()) {
String bDay = cursor.getString(bDayColumn);
Log.d(TAG, "Birthday: " + bDay);
}

You need to first get a list of all contact-ids that has birthdays, then query for the phones of all those contacts, and then print the combined results.
Cursor cursor = getContactsBirthdays();
// get contact-ids for phones query
List<String> ids = new ArrayList<>();
while (cursor.moveToNext()) {
ids.add(cursor.getString(1));
}
String[] projection = new String[] { Phone.NUMBER, Phone.CONTACT_ID };
StringBuilder where = new StringBuilder(Data.MIMETYPE + " = " Phone.CONTENT_ITEM_TYPE + " AND " + Contacts.CONTACT_ID + " IN (");
for (String id : ids) {
where.append(id).append(",");
}
where.deleteCharAt(where.length() - 1);
where.append(")");
Cursor cur2 = getContentResolver().query(Data.CONTENT_URI, projection, where.toString(), null, null);
Map<Long, String> contactIdToPhone = new HashMap<>();
while (cur2.moveToNext()) {
contactIdToPhone.put(cur2.get(1), cur2.get(0));
}
cur2.close();
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
Long id = cursor.getLong(1);
Log.i(TAG, "Birthday: id=" + id + ", name=" + cursor.getString(0) + ", date=" + cursor.getString(2) + ", phone=" + contactIdToPhone.get(id));
}
cursor.close();

Related

Cursor query order by Date

I have a TextView to which I'm putting my contacts which have birthdays:
private String loadContacts()
{
StringBuilder builder = new StringBuilder();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null,
null, null);
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE +
" = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE +
"' and " + ContactsContract.Data.CONTACT_ID + " = " + id;
String sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE + " ASC";
Cursor birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where,
null, sortOrder);
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.
getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
builder.append("Contact: ").append(name).append(" ").append(birthday).append("\n\n");
}
}
birthdayCur.close();
}
}
cursor.close();
return builder.toString();
}
And then assign the contacts on the "onCreate" function
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_CONTACTS }, 1);
} else {
listContacts.setText(loadContacts());
}
This line of code:
String sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE + " ASC";
Cursor birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where,
null, sortOrder);
doesn't seem to work no matter what I put there to order it (name, _ID etc.).
I am trying to sort by Birthdays but even if I try to sort by name it doesn't work. Why ?
Am I using wrong type of View(TextView) or is it the way I use StringBuilder to set the text or something else entirely?
My minSdkVersion is 19 and targetSdkVersion 26. I'm testing this App on my Nexus5(api 23 android 6.01) on debugging mode.
I appreciate any advice.
Well this is what happens when I hurried. It was actually beyond simple.
I just needed to put all my needed columns in the first Cursor and the second more important thing was to use "ContactsContract.Data.CONTENT_URI"
instead of "ContactsContract.Contacts.CONTENT_URI" because the "DATA.CONTENT_URI" actually has all of my needed columns and "Contacts.CONTENT_URI" doesn't.
As simple as that.
private String loadContacts()
{
StringBuilder builder = new StringBuilder();
ContentResolver cr = getContentResolver();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.Contacts.DISPLAY_NAME
};
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE +
" = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "'";
String sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE + " ASC";
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
columns, where,
null, sortOrder);
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String birthday = cursor.getString(cursor.
getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
builder.append("Contact: ").append(name).append(birthday).append(" ").append("\n\n");
}
}
cursor.close();
return builder.toString();
}

Android: Retrieve Name, Phone Number, Email, Birthday from Contact

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);
}

Android search contacts by phone number and contact name (Both in same time)

I want to query on contacts by phone number and contact name in same time with "LIKE" operator, here is my code :
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1 AND (" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " LIKE '" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' ) ", null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
return cursor;
But my code does not work, it's crashes and android says "data4" and "data1" column does not exist.
Use below code to find contact by name
public String findByName(Context context , String name) {
String result= null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if (c.moveToFirst()) {
result= c.getString(0);
}
c.close();
if(result==null)
result= "This contact is not saved into your device";
return result;
}
Use loader to get fastest results.
public Loader<Cursor> getContactCursor(Context context, Bundle args) {
Uri baseUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String filter = args != null ? args.getString("filter") : null;
if (filter != null && filter.length() > 0) {
return new CursorLoader(context,baseUri, null, "(display_name LIKE ?) OR (data1 LIKE ?)", new String[]{"%" + filter + "%","%" + filter + "%"}, null);
}else{
return new CursorLoader(context,baseUri, projection,null, null, null);
}
}

Android Applicaiton - How to get birthday of a contact

I am working on an android application for which I need to match the birthday of each contact against current date and if positive, process some business logic, which needs the complete contact details.
I have found ways to read birthdays of contacts or the contacts themselves separately, but am confused as to how to combine both. Can somebody please provide some direction.
Thanks
Found the answer after some looking out on the web. The way this has to be done is :
Get list of contacts
For each contact, get contactId
Get birthday using the contactid
Following is the code snippet :
ContentResolver cr = getContentResolver(); //getContnetResolver()
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
while (cur.moveToNext()) {
Map<String, String> contactInfoMap = new HashMap<String, String>();
String contactId = cur.getString(cur.getColumnIndex(ContactsContract.Data._ID));
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};
String where = Event.TYPE + "=" + Event.TYPE_BIRTHDAY +
" and " + Event.MIMETYPE + " = '" + Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contactId;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
Cursor birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
}
}
birthdayCur.close();
}
cur.close();

Problem with Email ContentResolver

I'm using the following code to build a list of email addresses on the device to display on a ListActivity. Currently I can retrieve the email addresses ok, but they're coming up in the form: null (email#address.com) instead of name (email#address.com) which is not ideal. The code I'm using should be retrieving the names as well:
Cursor c = getContentResolver().query(Email.CONTENT_URI,
new String[]{Email.CONTACT_ID, Email.DISPLAY_NAME, Email.DATA},
null, null, null);
addresses = new String[c.getCount()];
try{
c.moveToFirst();
for(int i = 0;i<c.getCount();i++){
addresses[i] = c.getString(1) + " (" + c.getString(2) + ")";
c.moveToNext();
}
} finally {
c.close();
}
Does anyone know what I'm doing wrong?
I've used this (definitely works on Android 2.2 on the Incredible; no promises on 2.3).
String nameAndEmailOrder = "lower(" + ContactsContract.Data.DISPLAY_NAME + ") ASC";
String[] nameAndEmailProjection = new String[] {
ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA }
Cursor emails = activity.managedQuery(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
nameAndEmailProjection, null, null, nameAndEmailOrder);
emails.moveToFirst();
int nameColumn = emails.getColumnIndex(
ContactsContract.Data.DISPLAY_NAME);
int emailColumn = emails.getColumnIndex(
ContactsContract.CommonDataKinds.Email.DATA);
do {
Log.d("test", String.format("%s (%s)", emails.getString(nameColumn), emails.getString(emailColumn)));
} while (emails.moveToNext());
Try this query:
Cursor c = managedQuery(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Email.DATA},
null, null, null);
Try this query :
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[]{Data.CONTACT_ID, Data.DISPLAY_NAME, Email.ADDRESS},
Data.MIMETYPE + "=?", new String[] {Email.CONTENT_TYPE}, null);
addresses = new String[c.getCount()];
try{
c.moveToFirst();
for(int i = 0;i < c.getCount();i++){
addresses[i] = c.getString(1) + " (" + c.getString(2) + ")";
c.moveToNext();
}
} finally {
c.close();
}
Note: Email.ADDRESS will be converted to Data.DATA1.

Categories

Resources