How to retrieve Contact name and phone number in Android - android

I'm trying to retrieve contact list with there name and phone numbers. I try following code:
// Get a cursor over every contact.
Cursor cursor = getContentResolver().query(People.CONTENT_URI,
null, null, null, null);
// Let the activity manage the cursor lifecycle.
startManagingCursor(cursor);
// Use the convenience properties to get the index of the columns
int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);
int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
String[] result = new String[cursor.getCount()];
if (cursor.moveToFirst())
do {
// Extract the name.
String name = cursor.getString(nameIdx);
// Extract the phone number.
String phone = cursor.getString(phoneIdx);
result[cursor.getPosition()] = name + "-" +" "+ phone;
} while(cursor.moveToNext());
This code should return an array with the all contacts name and its phone number but this only returns name of the contact and returns NULL in phone number,
Example Output:
John - null

In Android manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Then in the activity:
editText.setOnFocusChangeListener(new OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
editText.setText("");
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
}
});
And then you have to catch the result of the action pick contact:
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
switch(reqCode)
{
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = managedQuery(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));
editText.setText(nameContact+ " "+ cNumber);
}
}
}
}
}

Don't use deprecated API access like as follow
Cursor cursor = getContentResolver().
query( Contacts.CONTENT_URI,
new String[]{Contacts.DISPLAY_NAME}, null, null,null);
if(cursor!=null){
while(cursor.moveToNext()){
Cursor c = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER, Phone.TYPE},
" DISPLAY_NAME = '"+cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME))+"'", null, null);
while(c.moveToNext()){
switch(c.getInt(c.getColumnIndex(Phone.TYPE))){
case Phone.TYPE_MOBILE :
case Phone.TYPE_HOME :
case Phone.TYPE_WORK :
case Phone.TYPE_OTHER :
}
}
}
}

Look on the sample code for retrieve the contacts from android mobile,
Cursor cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phones = context.getContentResolver().query(
Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
Log.i("TYPE_HOME", "" + number);
break;
case Phone.TYPE_MOBILE:
Log.i("TYPE_MOBILE", "" + number);
break;
case Phone.TYPE_WORK:
Log.i("TYPE_WORK", "" + number);
break;
case Phone.TYPE_FAX_WORK:
Log.i("TYPE_FAX_WORK", "" + number);
break;
case Phone.TYPE_FAX_HOME:
Log.i("TYPE_FAX_HOME", "" + number);
break;
case Phone.TYPE_OTHER:
Log.i("TYPE_OTHER", "" + number);
break;
}
}
phones.close();
cursor.close();

HellBoy is right, Phone.xxx is depricated. I did it that way with a lookup-uri:
Uri look = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, "23N9983726428fnwe");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(look);
Experiment with Contacts.xxx on the first line, you will find the right sollution.

Try the below code.
Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null, Phone.DISPLAY_NAME + " ASC");

package com.number.contatcs;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Main2Activity extends Activity {
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button getContacts = (Button) findViewById(R.id.button1);
getContacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (reqCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String number = "";
String lastName = "";
try {
Uri result = data.getData();
// get the id from the uri
String id = result.getLastPathSegment();
// query
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone._ID
+ " = ? ", new String[] { id }, null);
// cursor = getContentResolver().query(Phone.CONTENT_URI,
// null, Phone.CONTACT_ID + "=?", new String[] { id },
// null);
int numberIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
number = cursor.getString(numberIdx);
// lastName =
// cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
} else {
// WE FAILED
}
} catch (Exception e) {
// failed
} finally {
if (cursor != null) {
cursor.close();
} else {
}
}
EditText numberEditText = (EditText) findViewById(R.id.w);
numberEditText.setText(number);
// EditText lastNameEditText =
// (EditText)findViewById(R.id.last_name);
// lastNameEditText.setText(lastName);
}
}
}
}

Related

Duplicated contact on preference item

I'm creating a PreferencesActivity where I have 3 preference items. When I click on each of them, I load contacts to pick one. After selecting a contact, I save it's name and phone number and I show it in the preference item. This is the way I do it:
preferences.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="#string/contact">
<Preference
android:key="Contact1"
android:title="Contact 1"/>
<Preference
android:key="Contact2"
android:title="Contact 2"/>
<Preference
android:key="Contact3"
android:title="Contact 3"/>
</PreferenceCategory>
</PreferenceScreen>
UserSettingsActivity.java extending PreferenceActivity
SharedPreferences mPreferences;
Preference contact1;
Preference contact2;
Preference contact3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
contact1 = findPreference("Contact1");
contact2 = findPreference("Contact2");
contact3 = findPreference("Contact3");
contact1.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_1);
return false;
}
});
contact2.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_2);
return false;
}
});
contact3.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_3);
return false;
}
});
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri contactData = data.getData();
switch(reqCode) {
case (PICK_CONTACT_1):
if (resultCode == RESULT_OK){
String contactID = null;
String contactNumber = null;
String contactName = null;
/*Get contact ID*/
Cursor cursorID = getContentResolver().query(contactData, new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
/*Get contact number using ID*/
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID}, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
/*Get name*/
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
/*Show on preferences*/
contact1.setTitle(contactName);
contact1.setSummary(contactNumber);
}
case (PICK_CONTACT_2):
if (resultCode == RESULT_OK){
String contactID = null;
String contactNumber = null;
String contactName = null;
/*Get contact ID*/
Cursor cursorID = getContentResolver().query(contactData, new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
/*Get contact number using ID*/
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID}, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
/*Get name*/
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
/*Show on preferences*/
contact2.setTitle(contactName);
contact2.setSummary(contactNumber);
}
case (PICK_CONTACT_3):
if (resultCode == RESULT_OK){
String contactID = null;
String contactNumber = null;
String contactName = null;
/*Get contact ID*/
Cursor cursorID = getContentResolver().query(contactData, new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
/*Get contact number using ID*/
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID}, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
/*Get name*/
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
/*Show on preferences*/
contact3.setTitle(contactName);
contact3.setSummary(contactNumber);
}
}
}
The problem is that when I set a contact for Contact1, also Contact2 and Contact3 are getting the same contact. Is the first time I'm working with preferences so I don't know what could be the reason for this.
The problem isn't with the Preferences but rather, with the switch statement.
You need to break at the end of each statement. Without a break, statements after a matching case label will be executed sequentially, regardless of the expressions of subsequent case labels.
Just include a break statement to prevent the statements in your switch blocks from falling through:
switch(reqCode) {
case (PICK_CONTACT_1):
---------
---------
break;
case (PICK_CONTACT_2):
---------
---------
break;
case (PICK_CONTACT_3):
---------
---------
break;
}

Android:- Select Contact and call to selected number

I have textview. Clicking on it opens up native contact list. Once the users selects a contact, i should display the number in my app. I could display the name but not able to display number. Please help.
Thanks in Advance.
This is my code but after selecting the contact my app crashes."Unfortunately 'app_name' has stopped"
public void dail(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}
Try this in your onActivity result. It will work.
ContentResolver cr = getContentResolver();
cursor = cr.query(intent.getData(), null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer
.parseInt(cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
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();
} else {
snipp.showAlertDialog(getApplicationContext(), "No Number",
"Cannot read number", false);
}
}
cursor.close();
Try out as below in your onActivityResult
ContentResolver cr = getContentResolver();
Uri contactData = data.getData();
Log.v("Contact", contactData.toString());
Cursor c = managedQuery(contactData,null,null,null,null);
if(c.moveToFirst()){
id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
Log.v("Contact", "ID: " + id.toString());
name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Contact", "Name: " + name.toString());
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
phone = pCur.getString(pCur .getColumnIndex(Phone.NUMBER));
Log.v("getting phone number", "Phone Number: " + phone);
}
}
}
Try this
Put this code in your textview OnclickListner
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
In Activity result put this code
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME))+" : "+c.getInt(c.getColumnIndexOrThrow(People.NUMBER));
//
txtContacts1.setText(name);
}
}
break;
}
For dail that no put this code
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getInt(c.getColumnIndexOrThrow(People.NUMBER)));
context.startActivity(intent);

How to get contacts' phone number in Android

My code is as below:
String[] columns = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, columns, null, null, null);
int ColumeIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
int ColumeIndex_DISPLAY_NAME = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int ColumeIndex_HAS_PHONE_NUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
while(cursor.moveToNext())
{
String id = cursor.getString(ColumeIndex_ID);
String name = cursor.getString(ColumeIndex_DISPLAY_NAME);
String has_phone = cursor.getString(ColumeIndex_HAS_PHONE_NUMBER);
if(!has_phone.endsWith("0"))
{
System.out.println(name);
GetPhoneNumber(id);
}
}
cursor.close();
public String GetPhoneNumber(String id)
{
String number = "";
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID + " = " + id, null, null);
if(phones.getCount() > 0)
{
while(phones.moveToNext())
{
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
System.out.println(number);
}
phones.close();
return number;
}
I get contacts' name success, but get phone number fail in GetPhoneNumber().
The phones.getCount() always equal 0.
How can I modify?
Android Contact API For 2.0
//
// Find contact based on name.
//
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();
For more information see this link
try this.
ContentResolver cr = 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));
Log.i("Names", name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
}
phones.close();
}
}
}
You need permission like -
android:name="android.permission.READ_CONTACTS"/>
Then, Calling the Contact Picker
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
Then,
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
// TODO Whatever you want to do with the selected contact name.
}
}
break;
}
}
Old question but I don't see the following answer here.
private static final String[] PROJECTION ={
ContactsContract.Contacts._ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
ContactsContract.Contacts.LOOKUP_KEY,
};
new CursorLoader(
this,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,
null,
null,//mSelectionArgs,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
);
Use column index ContactsContract.CommonDataKinds.Phone.NUMBER to retreive the phone number from the cursor.
U can use contact picker.
Call contact picker on any button and use the below code :
|*| Add in : AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS"/>
|*| Add in : activity_name.java
void calContctPickerFnc()
{
Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(calContctPickerIntent, 1);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data)
{
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode)
{
case (1) :
if (resultCode == Activity.RESULT_OK)
{
Uri contctDataVar = data.getData();
Cursor contctCursorVar = getContentResolver().query(contctDataVar, null,
null, null, null);
if (contctCursorVar.getCount() > 0)
{
while (contctCursorVar.moveToNext())
{
String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));
String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.i("Names", ContctNamVar);
if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", ContctMobVar);
}
}
}
}
break;
}
}
Your can add this code on your Activity class:
private final int PICK_CONTACT = 5;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
//Your code
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT && resultCode == RESULT_OK) {
Uri contactData = data.getData();
Cursor phones = getContentResolver()
.query(contactData,
null,
null,
null,
null);
String name = "", phoneNumber = "";
while (phones.moveToNext()) {
name = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
}

Get number from Contacts into EditText android [duplicate]

I am trying to get a contacts name and phone number after a user has picked a contact from the Contact Picker. I am attempting to make my application work for SDK v3 and up so I created an abstract class that would call only the API that I needed. I already have the abstract class working (it chooses the right API) and I also have the API for SDK v3,4 working. I am having problems getting the newer API that uses ContactsContract to work.
I can get a contacts name, but the number it retrieves is always the number for the contact ID BEFORE it! Example: I have 2 contacts "John Doe" and "Jane Doe" with respective numbers "555-555-555" and "777-777-7777" added in the contacts. John Doe is ID=1 and Jane Doe is ID=2. If I attempt to get Jane Doe's number, I get John's, 555-555-5555. If I attempt to get John's, I don't get anything. The check for if (cursor.moveToNext()) fails.
Can you please help me fix this? It is driving me crazy. I have looked at many many examples and always get the same error.
The Intent data is the data Intent from the onActivityResult
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
class NewContactsAdapterBridge extends ContactsAdapterBridge {
ArrayList<String> info = new ArrayList<String>();
ArrayList<String> getInfo (Activity a, Intent data) {
Uri contactData = data.getData();
Cursor cursor = a.managedQuery(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
String id = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow
(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhoneNumber = cursor.getString(cursor.getColumnIndexOrThrow(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
info.add(name);
if (Integer.parseInt(hasPhoneNumber) > 0) {
Uri myPhoneUri = Uri.withAppendedPath(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
id);
Cursor pCur = a.managedQuery(
myPhoneUri,
null,
null,
null,
null);
if (pCur.moveToNext()) {
String number = pCur.getString( pCur.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
info.add(number);
}
}
}
return info;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
Cursor cursor = null;
String phoneNumber = "";
List<String> allNumbers = new ArrayList<String>();
int phoneIdx = 0;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
phoneNumber = cursor.getString(phoneIdx);
allNumbers.add(phoneNumber);
cursor.moveToNext();
}
} else {
//no results actions
}
} catch (Exception e) {
//error actions
} finally {
if (cursor != null) {
cursor.close();
}
final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
builder.setTitle("Choose a number");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String selectedNumber = items[item].toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
}
});
AlertDialog alert = builder.create();
if(allNumbers.size() > 1) {
alert.show();
} else {
String selectedNumber = phoneNumber.toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
}
if (phoneNumber.length() == 0) {
//no numbers found actions
}
}
break;
}
} else {
//activity result error actions
}
}
You need to adapt this to work with your app
I dint get that line case CONTACT_PICKER_RESULT...the code i used above using this
int PICK_CONTACT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(Button) findViewById(R.id.button1);
et=(EditText) findViewById(R.id.editText1);
b.setOnClickListener(this);
//et.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
break;
// case R.id.editText1:
// break;
}
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
These code helps u ,I think the PICK activity only returns the ID of the contact picked. From that you could query the Contact provider and if there are multiple phone numbers, prompt the user to select one of them.
U can use this also
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
Cursor cursor = null;
String phoneNumber = "";
List<String> allNumbers = new ArrayList<String>();
int phoneIdx = 0;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
phoneNumber = cursor.getString(phoneIdx);
allNumbers.add(phoneNumber);
cursor.moveToNext();
}
} else {
//no results actions
}
} catch (Exception e) {
//error actions
} finally {
if (cursor != null) {
cursor.close();
}
final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
builder.setTitle("Choose a number");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String selectedNumber = items[item].toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
}
});
AlertDialog alert = builder.create();
if(allNumbers.size() > 1) {
alert.show();
} else {
String selectedNumber = phoneNumber.toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
}
if (phoneNumber.length() == 0) {
//no numbers found actions
}
}
break;
}
} else {
//activity result error actions
}
}
Kind note for beginners, Don't forget to include the following permission or else it wont work
<uses-permission android:name="android.permission.READ_CONTACTS"/>
switch (reqCode) {
case (REQUEST_CODE_email):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String num = "";
if (Integer.valueOf(hasNumber) == 1) {
Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (numbers.moveToNext()) {
num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();
//asdasdasdsa
if(getEmail(num).isEmpty()){
Toast.makeText(this, "Email Not Found In That Contact Try Another", Toast.LENGTH_SHORT).show();
}
else {
edt_email_contact.setText("" + getEmail(num));
} }
}
}
break;
}
case (REQUEST_CODE_number):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String num = "";
if (Integer.valueOf(hasNumber) == 1) {
Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (numbers.moveToNext()) {
num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();
//asdasdasdsa
edt_email_contact.setText("" + num);
}
}
}
break;
}
}

contacts picker, retrieving last name, first name, phone number

Right now, I'm able to retrieve the phone number and set the text of my editText to that number. But when I try to get the last name or first name it doesn't work. Note the stuff I commented out.
Heres my code:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class main extends Activity {
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button getContacts = (Button)findViewById(R.id.getContacts);
getContacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if(resultCode == RESULT_OK) {
switch (reqCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String number = "";
String lastName ="";
try {
Uri result = data.getData();
//get the id from the uri
String id = result.getLastPathSegment();
//query
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone._ID + " = ? " , new String[] {id}, null);
// cursor = getContentResolver().query(Phone.CONTENT_URI,
// null, Phone.CONTACT_ID + "=?", new String[] { id },
// null);
int numberIdx = cursor.getColumnIndex(Phone.DATA);
if(cursor.moveToFirst()) {
number = cursor.getString(numberIdx);
//lastName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
} else {
//WE FAILED
}
} catch (Exception e) {
//failed
} finally {
if (cursor!=null) {
cursor.close();
}
EditText numberEditText = (EditText)findViewById(R.id.number);
numberEditText.setText(number);
//EditText lastNameEditText = (EditText)findViewById(R.id.last_name);
//lastNameEditText.setText(lastName);
}
}
}
This is how i got the display name...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
//Get Name
cursor = getContentResolver().query(result, null, null, null, null);
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
} catch (Exception e) { }
}
}
}
Hope it helps :)
If you have your contact id, you can use this method for retrieving all the other contact data:
Map<String, String> result = new HashMap<>();
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.CONTACT_ID + "='" + YOUR_CONTACT_ID + "'", null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String mime = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
switch (mime) {
case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
result.put(FIRST_NAME, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)));
result.put(LAST_NAME, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)));
break;
case ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE:
result.put(CITY, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)));
result.put(STREET, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)));
result.put(ZIP, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)));
break;
case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
if (ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE == cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))) {
result.put(MOBILE, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
break;
}
}
cursor.close();
}
return result;

Categories

Resources