Getting Contacts numbers - android

I am having problem getting the number of contact that i have selected. In my app I call the built in application for contacts as a new activity, when you choose a contact the activity returns his name, now I need it to return all the numbers that the user entered for that contact. I found the code in some tutorial on the internet... Here is the code
This is how i call the contact activity
mSuspectButton = (Button) v.findViewById(R.id.crime_suspect);
mSuspectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, REQUEST_CONTACT);
}
});
This is how i get the name of the selected contact:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_CONTACT) {
Uri contactUri = data.getData();
// Specify which fields you want your query to return
// values for.
String[] queryFields = new String[] {
ContactsContract.Contacts.DISPLAY_NAME };
// Perform your query - the contactUri is like a "where"
// clause here
Cursor c = getActivity().getContentResolver().query(contactUri,
queryFields, null, null, null);
// Double-check that you actually got results
if (c.getCount() == 0) {
c.close();
return;
}
// Pull out the first column of the first row of data -
// that is your suspect's name.
c.moveToFirst();
String suspect = c.getString(0);
mCrime.setSuspect(suspect);
mSuspectButton.setText(suspect);
c.close();
}
}
So please can anyone help, I really don't understand how these works?

Use this in your onActivityResult, this will return you the selected number
#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));
}
}
}
}
}

1) Write this code to fetch all contact numbers and names.
2) Add them in separate arraylists.
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 phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");
alContactNames.add(name);
alContactNumbers.add(phoneNumber);
}
phones.close();
3) make listview in your app with custom adapter. In each list item, there needs to be the contact number , contact name and check box for selection.
this will solve your problem.

Related

Android - back from Contacts intent without selecting one

In my android application I have a list of people (name and telephone number) and I let the user add a person to the app's database by importing one from their contacts list. Everything works fine, but a user could click the button to import a new person and then go back, so the Contacts intent will be closed without actually selecting a contact.
So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();
// Retrieve the name from the DISPLAY_NAME column
String name = cursor.getString(cursor.getColumnIndex(ontactsContract.Contacts.DISPLAY_NAME));
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);
// update database
dbManager.addPerson(name, number, true);
}
}
}
So how can I check if the user actually selected a contact or went back?
So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.
You already have the code for this: if (resultCode == RESULT_OK). If the user presses BACK, you will not get RESULT_OK.
You are using an startActivityForResult which will return you back to the same activity once your
Intent.ACTION_PICK, Uri.parse("content://contacts")
jobs gets over that is the user has selected a contact.
And in order to get the name , number or any other details of the contact selected you do it in your onActivityResult callback like follows :
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if(reqCode == PICK_CONTACT_REQUEST) {
String cNumber = null;
String cName = null;
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
String hasPhone = null;
String contactId = null;
if (cursor != null) {
cursor.moveToFirst();
try {
hasPhone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
} catch (IllegalArgumentException e) {
Log.e(TAG, "Exception Message : " + e.getMessage());
DisplayMessage.error("Sorry can't access contacts. Check permissions settings.", this);
return;
}
if (hasPhone != null && hasPhone.equals("1")) {
Cursor phones = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
if (phones != null) {
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");
cNumber = phoneNumber;
}
phones.close();
}
cName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.d(TAG, "Contact name is:" + cName);
}
cursor.close();
}
}
}
}

Retrieve all numbers from one contact issue

I know this is a common question since I found many answers about it, but I still have an issue regarding phone number retrieving.
I want to get ALL numbers from one contact picked from the PICK_CONTACT activity.
Here is my code from the onActivityResult() block
#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) {
ArrayList<String> allContacts = new ArrayList<String>();
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
while (c.moveToNext()) {
String contact_id = c.getString(c.getColumnIndex( _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 + " = ?", new String[] { contact_id }, null);
while (phones.moveToNext())
{
String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
allContacts.add(contactNumber);
break;
}
phones.close();
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
TXT_EmergencyContactNameProfile.setText(name);
}
}
break;
}
}
I expected the loop while (phones.moveToNext()) to get all different numbers ... but no
Thank you very much in advance ;)
Try to delete the "break;" inside the while loop.

How to get phone number type label from given phone number in android

I tried to print Contact name(Eg. "Jose") & Contact phone number type value(Eg. "Home","Work",etc.,) from phone contact for given particular phone number(Eg. "9600515852")
for this i used bellow code. but i can able get Contact name only. i am getting app crash when i am trying to get the phone number type.
Please guide me.
String number = getContactName(this, "9600515852");
Toast.makeText(getApplicationContext(),number,Toast.LENGTH_LONG).show();
private String getContactName(Context context, String number) {
String TAG ="" ;
String name = null, label=null;
int type=0;
// define the columns I want the query to return
String[] projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,ContactsContract.PhoneLookup._ID };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
// type = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name+" - "+number;
}
use
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
instead of
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
In My case, On button click getting contact information from Contacts app is like this. And it is working
Call an Intent
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
Handle the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (1):
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.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String resultedPhoneNum = pop.getContactNumber(id, MainActiv.this);
String resultedName=pop.getContactName(name, MainActiv.this);
contactName.setText(resultedName);
}
}
break;
}
}
Hope that helps!
Well the correct approach is to include the Phone.TYPE in your Projection query. It contains only DISPLAY_NAME andID and it crashes as there is no field as "type" included in your query.
This will definitely solve your issue.
Try this:
type = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.TYPE));

how can i get phone number of selected contact

c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent i = new Intent(ContactsContract.Contacts.CONTENT_TYPE);
Intent i = new Intent(Intent.ACTION_PICK);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(i, CONTACT_PICKER_RESULT); }
});
}
public void onActivityResult(int requestCode ,int resultCode ,Intent data) {
if ((requestCode == CONTACT_PICKER_RESULT) && (resultCode == RESULT_OK)) {
}
}
This code contains the intent opens the contacts but I need if select contact take a contact phone number then set it to string
Check this solution: How to call Android contacts list?
Its pretty much what you need to do but instead name you should search the number with the cursor.
PS: Next time search better, there is alot of people asking it.
You can try this.
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
if(reqCode == this.pickContact){
if (resultCode == Activity.RESULT_OK) {
Log.d("ContactsH", "ResOK");
Uri contactData = data.getData();
Cursor contact = getContentResolver().query(contactData, null, null, null, null);
if (contact.moveToFirst()) {
String name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Whatever you want to do with the selected contact's 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(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
// do something with the Home number here...
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
// do something with the Mobile number here...
Log.d("ContactsH", number);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();
}
}
}else{
Log.d("ContactsH", "Canceled");
}
}
That works for me.

search contacts and get the contact number from phone contacts in android

I am working with an app, in this I have to search contacts when the button click and select one of the contact from phone contacts. Finally I want to set it to edittext.I can able to search the contacts from phone contacts but I am unable to get contact from phone contacts.
activity:
searchBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent,1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_OK){
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String number = cursor.getString(cursor.getColumnIndexOrThrow
(ContactsContract.CommonDataKinds.Phone.NUMBER));
//contactName.setText(name);
ephoneNumber.setText(number);
//contactEmail.setText(email);
}
}
First set Intent for StartActivityForResult Like this
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
then deal with result what intent carry from native contact application
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}
see another reference links
Link 1
Link 2
Bharat,
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;
}
}
OR, In other way You can use
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
//...
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
Above solution is simple and working for contact number fetching.
try this
CursorLoader cursorLoader = new CursorLoader(mActivity,
CallLog.Calls.CONTENT_URI, null, null, null, null);
managedCursor = cursorLoader.loadInBackground();
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int name = managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
String conTactnumber=managedCursor.getString(number);
String contactname=managedCursor.getString(name);
set permission
<uses-permission android:name="android.permission.READ_CONTACTS" >
</uses-permission>

Categories

Resources