No phonenr from ContactsContract - android

Im having some trouble with getting a phone number from a contact using the ContactsContract
My code is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Bundle extras = data.getExtras();
Set<String> keys = extras.keySet();
Iterator<String> iterate = keys.iterator();
while (iterate.hasNext()) {
String key = iterate.next();
Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
}
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,null, Phone.CONTACT_ID + "=?", new String[] { id },null);
int PhoneIdx = cursor.getColumnIndex(Phone.NUMBER);
if (cursor.moveToFirst()) {
phone = cursor.getString(PhoneIdx);
Log.v(DEBUG_TAG, "Got number: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get Number", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText ponenumber = (EditText) findViewById(R.id.editPhone1);
ponenumber.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "Contact has no phone number",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
Whenever i run it and choose a contact i just get the "Contact has no phone number". I can't figure out why, anyone has any ideas?
Regards

You should use a "Phone picker" intent, not a "Contact picker":
static final int REQUEST_SELECT_PHONE_NUMBER = 1;
public void selectContact() {
// Start an activity for the user to pick a phone number from contacts
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == RESULT_OK) {
// Get the URI and query the content provider for the phone number
Uri contactUri = data.getData();
String[] projection = new String[]{CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection,
null, null, null);
// If the cursor returned is valid, get the phone number
if (cursor != null && cursor.moveToFirst()) {
int numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberIndex);
// Do something with the phone number
...
}
}
}
Taken from the docs at:
https://developer.android.com/guide/components/intents-common.html#Contacts
To have the user select a specific piece of information from a
contact, such as a phone number, email address, or other data type,
use the ACTION_PICK action and specify the MIME type to one of the
content types listed below, such as CommonDataKinds.Phone.CONTENT_TYPE
to get the contact's phone number.

Related

Get contact name from Whatsapp addess

I have this contact information from Whatsapp: 491766465xxxx#s.whatsapp.net
Obtained from this code
void startWhatsAppContactPicker() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setPackage("com.whatsapp");
try {
startActivityForResult(intent, REQUEST_CODE_PICK_WHATSAPP);
} catch (Exception e) {
Toast.makeText(this, "Kein Whatsapp installiert", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_PICK_WHATSAPP:
if (resultCode == RESULT_OK) {
if (data.hasExtra("contact")) {
String address = data.getStringExtra("contact");
Log.d(TAG, "The selected Whatsapp address is: " + address);
}
}
break;
default:
break;
}
}
Outputt: 49176646xxxx#s.whatsapp.net
Is this information stored in the Android contacts?
I need the contact to get the the name of the owner.
I have tryied this but without success:
How to get whatsapp Contacts from Android?
Cheers
Assuming the 49176646xxxx segment is a phone number, you can search the phone contacts for that phone number:
String address = data.getStringExtra("contact");
String phone = address.split("#")[0];
String[] projection = new String[] {Phone.DISPLAY_NAME, Phone.NUMBER, Phone.NORMALIZED_NUMBER };
String selection = Phone.NORMALIZED_NUMBER + " = " + phone;
Cursor c = cr.query(Phone.CONTENT_URI, projection, selection, null, null);
if (c != null && c.moveToFirst()) {
Log.d(TAG, "name is: " + c.getString(0));
}
(note: Phone.NORMALIZED_NUMBER was added in API 16)

Android query for email with given email id

I let the user choose email from contacts with following intent:
Intent emailPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Email.CONTENT_URI);
startActivityForResult(emailPickerIntent, Constants.CONTACT_PICKER_RESULT);
How can I query for the email the user chose in onActivityResult method?
Following code will help you to get the email address onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "", name = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email._ID + "=" + id, null, null);
int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
name = cursor.getString(nameId);
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.editTextv);
EditText personEntry = (EditText) findViewById(R.id.person);
emailEntry.setText(email);
personEntry.setText(name);
if (email.length() == 0 && name.length() == 0)
{
Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
}
You also have to add following permission in your manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS"/>

Accessing contacts list, searching for a contact, pulling its number and finally dial (android)

My app gets a contact name from the user, and then it is supposed to search in the contacts list if the contact exists. If it does, then pull its number and then automatically dial this number.
I can't seem to understand how to look for the contact name and then pull its number, if it exists.
public boolean seekAction(String s)
{
Intent callIntent= new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
callIntent.setType(Phone.CONTENT_TYPE);
if (callIntent.resolveActivity(getPackageManager()) != null)
{
startActivityForResult(callIntent, CONTACT_CALL_CODE_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK)
{
if(requestCode == CONTACT_CALL_CODE_REQUEST)
{
// Get the URI and query the content provider for the phone number
Uri contactUri = data.getData();
String[] s = new String[]{Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, s, null, null, null);
// If the cursor returned is valid, get the phone number
if (cursor != null && cursor.moveToFirst())
{
int numberIndex = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(numberIndex);
// Do something with the phone number
Log.i("actionCallResult()", "phone number= "+number);
Intent intent = new Intent(Intent.ACTION_DIAL);//calling intent
intent.setData(Uri.parse("tel:" + number));
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
I have this code, but it doesn't help me to look for the contact by its name.
edit:
public boolean actionCallResult(String str)
{
Log.i("actionCallResult()", "inside actionCallResult");
Cursor contacts = getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
boolean contactFound = false; // If the cursor returned is valid, get the phone number
if (contacts != null && contacts.moveToFirst())
{
do{
String contactName = contacts.getString(contacts.getColumnIndex(Phone.DISPLAY_NAME));
if (contactName.contains(str)) //contactName.equals(str)
{
contactFound = true;
break;
}
else
{
if(str.charAt(0)== 'ל')
{
if (contactName.contains(str.substring(1)))
{
contactFound = true;
break;
}
}
}
}while (contacts.moveToNext());
}
if(contactFound)
{
String number= contacts.getString(contacts.getColumnIndex(Phone.NUMBER));
Log.i("actionCallResult()", "phone number= "+number);
Intent intent = new Intent(Intent.ACTION_DIAL);//calling intent
intent.setData(Uri.parse("tel:" + number));
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
}
contacts.close();
return contactFound;
}
I wrote a simple code that looks for a contact named "Mike Peterson" and toasts a message with the contact's number if found, and a "not found" message otherwise.
This code is raw and by no means should serve any professional implementations. A better approach would be to use custom AsyncTasks and Array Storage.
Please note that this following permission declaration must appear in your manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
The following was tested under a simple main activity:
String str = "Mike Peterson"; // As an example
Cursor contacts = getApplicationContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
boolean contactFound = false;
while (contacts.moveToNext()) {
String contactName =
contacts.getString(contacts.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (contactName.equals(str)) {
contactFound = true;
break;
}
}
Toast.makeText(getApplicationContext(), contactFound ?
contacts.getString(contacts.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER)) : "Contact not found!"
, Toast.LENGTH_LONG).show();
contacts.close();

Contacts wont show up into EditText

I have an application that is supposed to call the contacts phone number into the designated EditText View. I have the button that calls up the contact picker and it works fine but when I click on it it doesn't add the information that I want into the View.
MY ONCLICKlISTENER
public void pickContact(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, GET_CONTACT);
}
MY STARTACTIVITYFORRESULT
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case GET_CONTACT:
Cursor cursor = null;
String Number = "";
try {
Uri result = data.getData();
Log.v(NOTIFICATION_SERVICE, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
Number = cursor.getString(emailIdx);
Log.v(NOTIFICATION_SERVICE, "Got number: " + Number);
} else {
Log.w(NOTIFICATION_SERVICE, "No results");
}
} catch (Exception e) {
Log.e(NOTIFICATION_SERVICE, "Failed to get number data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText mNumbers = (EditText)findViewById(R.id.editNumber);
mNumbers.setText(Number);
if (Number.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(NOTIFICATION_SERVICE, "Warning: activity result not ok");
}
}
Thanks for any help.
Make sure you add
<uses-permission android:name="android.permission.READ_CONTACTS" />
to your manifest
hey u have not used any Bundles in your code.
Viz: Bundle extras = data.getExtras
For Complete Reference, Check out the site: http://mobile.tutsplus.com/tutorials/android/android-essentials-using-the-contact-picker/

Android Contact list getting phone number

hi i am trying this code in my app i can get the contact list but when i press on contact name i didnt get any thing in my edittext which i expected to get the contact phone number
sorry about my poor english
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode=RESULT_OK) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Bundle extras = data.getExtras();
Set<String> keys = extras.keySet();
Iterator<String> iterate = keys.iterator();
while (iterate.hasNext()) {
String key = iterate.next();
Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
}
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int PhoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
phone = cursor.getString(PhoneIdx);
Log.v(DEBUG_TAG, "Got number: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to Number", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText ponenumber = (EditText) findViewById(R.id.ednum);
ponenumber.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
You're actually really close- A few things.
Your switch statement is basing off of the resultCode, not the request code. Change that- It should read "switch(requestCode)"
Phone.DATA will work, but use Phone.NUMBER instead for readability sake:)
Make sure you have the permission for android.permission.READ_CONTACTS set in your AndroidManifest.xml file, as an element inside the manifest element, but not in the application element. The line should should look like this.
<uses-permission android:name="android.permission.READ_CONTACTS" />
I made those modifications to your sample, and got working code.
you can change you code that you want get phone number,as the following
List numberList = new ArrayList();
Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,contactId);
Uri targetUri = Uri.withAppendedPath(baseUri,Contacts.Data.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(targetUri,
new String[] {Phone.NUMBER},Data.MIMETYPE+"='"+Phone.CONTENT_ITEM_TYPE+"'",null, null);
startManagingCursor(cursor);
while(cursor.moveToNext()){
numberList.add(cursor.getString(0));
}
cursor.close();
It is an old post but it could help someone.
If you just have to Pick-up a contact, you can use the first code of the post without this part:
Bundle extras = data.getExtras();
Set<String> keys = extras.keySet();
Iterator<String> iterate = keys.iterator();
while (iterate.hasNext()) {
String key = iterate.next();
Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
}

Categories

Resources