Unable to get Phone from registerForActivityResult(new ActivityResultContracts.PickContact() - android

I am trying to get Contact information. It used to work fine when for years, but since (today) I start using registerForActivityResult(new ActivityResultContracts.PickContact() I get various columns (listed below) for null projection, but I am unable to get phone and email directly. Also, it doesn't recognize Phone.CONTACT_ID Can I get sample code to get both Phone and Email using registerForActivityResult.
last_time_contacted, phonetic_name, is_private, custom_ringtone, contact_status_ts, pinned, photo_id, photo_file_id,
contact_status_res_package, link_count, link, contact_chat_capability, contact_status_icon, display_name_alt, sort_key_alt, in_visible_group, starred, contact_status_label,
phonebook_label, is_user_profile, has_phone_number, display_name_source, has_email, phonetic_name_style, send_to_voicemail, lookup, phonebook_label_alt,
contact_last_updated_timestamp, sec_custom_vibration, photo_uri, phonebook_bucket, sec_preferred_sim, contact_status, display_name, sort_key, photo_thumb_uri, link_type1,
contact_presence, sec_custom_alert, sec_led, display_name_reverse, in_default_directory, times_contacted, dirty_contact, _id, name_raw_contact_id, phonebook_bucket_alt
New Code (Very similar to old code)
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();
id = cursor.getString(cursor.getColumnIndex(Phone.CONTACT_ID));
String number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
String name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
Old Code:
Intent pickContactIntent = new Intent(Intent.ACTION_PICK);
pickContactIntent.setType(Phone.CONTENT_TYPE);
startActivityForResult(pickContatIntent, PICK_CONTACT_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri contactUri = data.getData();
String[] projection = {Phone.CONTACT_ID, Phone.NUMBER, Phone.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
cursor.moveToFirst();
id = cursor.getString(cursor.getColumnIndex(Phone.CONTACT_ID));
String number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
String name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));

Related

Views contact details and get phone number selected by user

I want to display the native android contacts list and then once the user picks a contact, i would like to move to the next native screen where it shows the details of the contact (like phone numbers, email, etc).
Now once the user selects either an email address or a phone number, I would then like to get that data back to my original activity and do further processing.
I know that I could use
startActivityForResult(new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACT);
and then myself parse the contact using getContentResolver().query() and then store each of the required fields. Then finally display on a separate activity as contact details and then once the user chooses any one of the phone numbers or emails, then i use that to do further processing.
I tried to do the following inside onActivityResult():
Uri contactData = data.getData();
Intent intent = new Intent(Intent.ACTION_PICK, contactData);
startActivityForResult(intent, REQUEST_CODE_PICK_CONTACT_DETAIL);
This displays the details of the contact but when the user selects a particular number, android calls it instead of passing it back to me in the previous activity.
But I would like to use the native screens if possible and it would require a lot less parsing and no extra activities/fragments.
Could someone suggest how to go about doing this?
Thanks
You can get contact details from phone contact doing this way
Uri uri = data.getData();
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = getActivity().getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int type = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
people.moveToFirst();
do {
String name = people.getString(indexName);
String number = people.getString(indexNumber);
System.out.println(name+number);
} while (people.moveToNext());
This might help:
Uri contactData = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = cr.query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c
.getString(c
.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + id, null, null);
phones.moveToFirst();
String cNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(), cNumber,
Toast.LENGTH_SHORT).show();
String nameContact = c
.getString(c
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
// contact number = cNumber
//contact name = nameContact
}
}

How to obtain the name of a caller from the phone number in Android

I am working in Android and I would like to know how to find out the contact name of a phone number.
In the BroadcastReceiver I have this:
String phonenr=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
I need the contact name ( full name - firstname + familyname , if there is) for this phone number.
Thx!
You can Try this link
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME} .....)
Use the function Below like this:
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("your receive phone number"));
Cursor phones = getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);
while (phones.moveToNext())
{
//it returns contact name
String name=phones.getString(phones.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
Check this out Retrieving Contact Information
//query for the people in your address book
Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null,People.NAME + " ASC");
startManagingCursor(cursor);
//bind the name and the number fields
String[] columns = new String[] { People.NAME, People.NUMBER };
int[] to = new int[] { R.id.name_entry, R.id.number_entry };
SimpleContactAdapter mAdapter = new SimpleContactAdapter(this, R.layout.list_entry, cursor, columns, to);
this.setListAdapter(mAdapter);

Android - Find a contact by display name

I'm trying to find a contact by display name. The goal is to open this contact and add more data to it (specifically more phone numbers), but I'm struggling to even find the contact I want to update.
This is the code I'm using:
public static String findContact(Context context) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI;
String[] projection = new String[] { PhoneLookup._ID };
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ?";
String[] selectionArguments = { "John Johnson" };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null);
if (cursor != null) {
while (cursor.moveToNext()) {
return cursor.getString(0);
}
}
return "John Johnson not found";
}
I do have a contact called "John Johnson", but the method always returns "not found". I also tried searching for a contact with just one name, so that makes no difference.
I suspect that it's something wrong with the uri, selection or selection arguments, because I couldn't find any example online of searching for contacts with a given display name, and it seems display name is a special kind of information, different from for example a phone number.
Any ideas how I can achieve to find John Johnson?
UPDATE: I found out how to find a contact by display name:
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Data.CONTENT_URI;
String[] projection = new String[] { PhoneLookup._ID };
String selection = StructuredName.DISPLAY_NAME + " = ?";
String[] selectionArguments = { "John Johnson" };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null);
if (cursor != null) {
while (cursor.moveToNext()) {
return cursor.getString(0);
}
}
return "John Johnson not found";
This code returns the contact id of the first contact with display name "John Johnson". In my original code I had the wrong uri and the wrong selection in my query.
I thinks the issue may caused by the projection you set. Projection is used to tell android which column of data you want to query then you only give the id column so the display name won't return. Try to remove the projection to see whether it works.
-- Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null);
++ Cursor cursor = contentResolver.query(uri, null, selection, selectionArguments, null);
Change Your Query URI.
You are using a URI that is meant to filter only phones numbers:
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI;
You need to use a URI that has access to the display_name column, like this:
Uri uri = ContactsContract.Data.CONTENT_URI;
There's a decent breakdown of what URIs to use and when to use them on the Android SDK Documentation:
If you need to read an individual contact, consider using CONTENT_LOOKUP_URI instead of CONTENT_URI.
If you need to look up a contact by the phone number, use PhoneLookup.CONTENT_FILTER_URI, which is optimized for this purpose.
If you need to look up a contact by partial name, e.g. to produce filter-as-you-type suggestions, use the CONTENT_FILTER_URI URI.
If you need to look up a contact by some data element like email address, nickname, etc, use a query against the ContactsContract.Data table. The result will contain contact ID, name etc.
//method for gaining id
//this method get a name and make fetch it's id and then send the id to other method //named "showinformation" and that method print information of that contact
public void id_return(String name) {
String id_name=null;
Uri resultUri = ContactsContract.Contacts.CONTENT_URI;
Cursor cont = getContentResolver().query(resultUri, null, null, null, null);
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME + " = ?" ;
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,name};
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
id_name = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID));}
nameCur.close();
cont.close();
nameCur.close();
//for calling of following method
showinformation(id_name);
}
//method for showing information like name ,phone, email and other thing you want
public void showinformation(String id) {
String name=null;
String phone=null;
String email=null;
Uri resultUri = ContactsContract.Contacts.CONTENT_URI;
Cursor cont = getContentResolver().query(resultUri, null, null, null, null);
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID+ " = ?" ;
String[] whereNameParams1 = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,id};
Cursor nameCur1 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams1, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur1.moveToNext()) {
name = nameCur1.getString(nameCur1.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));}
nameCur1.close();
cont.close();
nameCur1.close();
String[] whereNameParams2 = new String[] { ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,id};
Cursor nameCur2 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams2, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur2.moveToNext()) {
phone = nameCur2.getString(nameCur2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));}
nameCur2.close();
cont.close();
nameCur2.close();
String[] whereNameParams3 = new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,id};
Cursor nameCur3 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams3, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur3.moveToNext()) {
email = nameCur3.getString(nameCur3.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));}
nameCur3.close();
cont.close();
nameCur3.close();
String[] whereNameParams4 = new String[] { ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE,id};
Cursor nameCur4 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams4, ContactsContract.CommonDataKinds.StructuredPostal.DATA);
while (nameCur4.moveToNext()) {
phone = nameCur4.getString(nameCur4.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DATA));}
nameCur4.close();
cont.close();
nameCur4.close();
//showing result
txadd.setText("Name= "+ name+"\nPhone= "+phone+"\nEmail= "+email);
}
//thank all persons in this site because of many help of me to learn and correction my warn and errors this is only a gift for all of you and ...
The below code should do the trick
if (displayName != null) {
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(displayName));
String[] displayNameProjection = { ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY, Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? ContactsContract.Contacts.DISPLAY_NAME_PRIMARY : ContactsContract.Contacts.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri, displayNameProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
} else {
return false;
}
Reference: Retrieving a List of Contacts Article

Android Contacts: how to get contact list with first name, last name and a picture

Is there a way to get all device contacts (aggregated, not raw) with contact ID, fist/last name, and contact picture?
Currently I am using the code below but it does not return structured name:
private static final String CONTACTS_SORT_ORDER = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// all contacts
public final String[] columns = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI};
c = contentResolver.query(Contacts.CONTENT_URI, null, null, null, CONTACTS_SORT_ORDER);
Thanks
It is not possible to fetch the required data with one query. For each contact ID you'll have to query its Data directory:
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri dataUri = Uri.withAppendedPath(contactUri, Contacts.Data.CONTENT_DIRECTORY);
Then you should run queries against this URI, filtering MIMETYPE by StructuredName.CONTENT_ITEM_TYPE to obtain StructuredName for the given ID.
Uri dataUri = Uri.withAppendedPath(contactUri, Contacts.Data.CONTENT_DIRECTORY);
Cursor nameCursor = getActivity().getContentResolver().query(
dataUri,
null,
Data.MIMETYPE+"=?",
new String[]{ StructuredName.CONTENT_ITEM_TYPE },
null);

Get Postal address from a contact using ContactsContract api on android

I am using ContactsContract api intent for showing all contacts from an activity. This intent returns an id of the contact. I need to get the postal address of this contact.
Here is the code which i am using for showing contacts:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
I am getting the result in the onActivityResult function.
Please help, how do i do this.
in your onActivityResult, first get the contact ID and query the ContactsContract.Data for the relevant data:
// get the contact ID
Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
cursor.moveToFirst();
long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
cursor.close();
// get the data package containg the postal information for the contact
cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[]{ StructuredPostal.STREET,
StructuredPostal.CITY,
// add more coluns from StructuredPostal if you need them
StructuredPostal.POSTCODE},
ContactsContract.Data.CONTACT_ID + "=? AND " +
StructuredPostal.MIMETYPE + "=?",
new String[]{String.valueOf(id), StructuredPostal.CONTENT_ITEM_TYPE},
null);
Street = cursor.getString(cursor.getColumnIndex(StructuredPostal.STREET));
Postcode = cursor.getString(cursor.getColumnIndex(StructuredPostal.POSTCODE));
City = cursor.getString(cursor.getColumnIndex(StructuredPostal.CITY)));
// etc.
Can be done this way too (little lesser code)
Send the Intent this way:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE); startActivityForResult(intent, PICK_CONTACT);
In the onActivityResult method
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String address = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
}
Kiran's answer probably works fine for Android 2.0 and above, but when you want it to be compatible for Android 1.6 and below you need to adapt the code a bit:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(Contacts.ContactMethods.CONTENT_POSTAL_TYPE);
startActivityForResult(intent, PICK_CONTACT);
And in onActivtyResult method:
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String address = c.getString(c.getColumnIndexOrThrow(Contacts.ContactMethodsColumns.DATA));
}
Where PICK_CONTACT is a int of your own choice. (Right?)
This will return all the addresses from the contact Postal Address.
Uri uri = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
String sortOrder = StructuredPostal.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cr = getContentResolver().query(uri,null, null, null, sortOrder);
while(cr.moveToNext())
{
String Street = cr.getString(cr.getColumnIndex(StructuredPostal.STREET));
String Postcode = cr.getString(cr.getColumnIndex(StructuredPostal.POSTCODE));
String City = cr.getString(cr.getColumnIndex(StructuredPostal.CITY));
Toast.makeText(this,"Address is : " +City+","+Street ,Toast.LENGTH_SHORT).show();
}
cr.close();

Categories

Resources