I'm writing an app that get contacts and all detail , such as any numbers in each contact. it works fine but i have a problem. as you see in below images when I call:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
first of all I see the (open from) screen like this:
and when i select " Contacts " the second screen is shown:
Is there any way that I call the the method, the second screen with contacts and detail numbers directly shown and i needless to see the first screen and select " Contacts ".
Thanks.
After all I found this way:
instead of:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
I have write these lines:
Intent intent = new Intent(Intent.ACTION_PICK,Uri.parse("content://contacts/people")); intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
I also had the same problem. Finally, I got rid of intermediate picker screen using below code,
Intent i=new Intent(Intent.ACTION_PICK);
i.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(i, SELECT_PHONE_NUMBER);
In onActivityResult get phone number as below
if (requestCode == 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[]{ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContext().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(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberIndex);
// Do something with the phone number
...
}
cursor.close();
}
Related
I'm trying to access the contact name, phone number, and address of a person which I selected from contact picker intent.
Here is the code which I am using to open the contact picker Intent :
Here is the code which I am using :
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
case PICK_CONTACT:
if (resultCode == Activity.RESULT_OK) {
System.out.println("in on ActivityResult");
Uri contactData = data.getData();
Cursor c = getActivity().managedQuery(contactData, null,
null, null, null);
if (c.moveToFirst()) {
String id =
c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));StringhasPhone=c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones getActivity().getContentResolver().query(ContactsContract.CommonDataKind s.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + id, null, null);
phones.moveToFirst();
String cNumber =
phones.getString(phones.getColumnIndex("data1"));String name phones.getString(phones.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
//here you can find out all the thing.
System.out.println("NAME:"+name);
}Cursor postal_cursor=getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.StructuredPostal.STREET,
ContactsContract.CommonDataKinds.StructuredPostal.CITY,
ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS},
ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.CommonDataKinds.StructuredPostal.MIMETYPE + "=?",
new String[]{String.valueOf(id),
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE},
null);
postal_cursor.moveToFirst();
while(postal_cursor.moveToNext())
{
String Strt =
postal_cursor.getString(postal_cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String Cty =
postal_cursor.getString(postal_cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String cntry =
postal_cursor.getString(postal_cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String address =
postal_cursor.getString(postal_cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
}
postal_cursor.close(); }
but I am not able to get the address which is stored.
Any help is appreciated. Thanks
If you don't have READ_CONTACTS permission, you'll only be able to get information from the Contacts.CONTENT_URI table, not specific info like phone or postal address.
If you'd like to get a phone, you can use the special phone-picker intent instead like:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_CODE);
or to get a postal address:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(CommonDataKinds.StructuredPostal.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_CODE);
See here: https://developer.android.com/guide/components/intents-common#PickContactDat
If you want to get both pieces of information, you'd need to ask the user for a READ_CONTACTS permissions for those queries to work.
I'm making an application in which user can add users from the application into his contacts.
Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION);
intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, bean.getMobileNo());
intent.putExtra(ContactsContract.Intents.Insert.NAME, bean.getName());
intent.putExtra(ContactsContract.Intents.Insert.EMAIL, bean.getEmailID());
startActivity(intent);
so adding it is not the issue the issue when it goes to add contact screen and if the user presses back button the contact is getting saved even if the user doesn't want to save the contact.
I want to do this using Intent only not through app. Is there any solution for this or is it device specific?
Try this
/**
* Open the add-contact screen with pre-filled info
*/
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.NAME, bean.getName());
intent.putExtra(ContactsContract.Intents.Insert.PHONE, bean.getMobileNo());
intent.putExtra(ContactsContract.Intents.Insert.EMAIL, bean.getEmailID());
context.startActivity(intent);
Try this,
// Declare
static final int PICK_CONTACT = 1;
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
//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 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();
cNumber = phones.getString(phones.getColumnIndex("data1"));
System.out.println("number is:" + cNumber);
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
break;
}
}
This may helps you.
If I understand your post properly, the issue is that regardless if the user wants to add a contact or not, the contact information gets added anyway.
As I noticed, you are already calling startActivity(intent), which saves the contact. Only run startActivity(intent) if the user has already approved/verified that he wants to add the contact. I suggest using a Dialog for the confirmation. If the user accepts, run startActivity(intent), if not, then simply disregard the action. Like so:
if (true){ // user accepts
Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION);
intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, bean.getMobileNo());
intent.putExtra(ContactsContract.Intents.Insert.NAME, bean.getName());
intent.putExtra(ContactsContract.Intents.Insert.EMAIL, bean.getEmailID());
startActivity(intent);
} else {
// your code here.
}
I think this post might also be useful for you. Cheers! :D
I know the intent for getting phone number
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, GET_CONTACT_NUMBER);
But I don't know how to get the phone number without requesting the contact read permission in onActivityResult().
Thanks.
Try Replacing your code with
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == GET_CONTACT_NUMBER) {
// 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...
}
}
}
Note: Before Android 2.3 (API level 9), performing a query on the
Contacts Provider (like the one shown above) requires that your app
declare the READ_CONTACTS permission (see Security and Permissions).
However, beginning with Android 2.3, the Contacts/People app grants
your app a temporary permission to read from the Contacts Provider
when it returns you a result. The temporary permission applies only to
the specific contact requested, so you cannot query a contact other
than the one specified by the intent's Uri, unless you do declare the
READ_CONTACTS permission.
Source: http://developer.android.com/training/basics/intents/result.html
I want to retrieve the mobile number from the contacts (I want to send an sms). Here my code:
//Selecting the contact
Button buttonPickContact = (Button)findViewById(R.id.pickcontact);
buttonPickContact.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, RQS_PICK_CONTACT);
}});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Cursor cursor = null;
mName.setText(context.getString(R.string.not_available));
mNumber.setText(context.getString(R.string.not_available));
if(requestCode == RQS_PICK_CONTACT && resultCode == RESULT_OK && data != null){
Log.d(TAG, "requestCode, resultCode, data ok");
Uri uri = data.getData();
try{
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER};
// cursor = getContentResolver().query(uri, projection, null, null, null);
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
Log.d(TAG, "Trying to retrieve the name and the number");
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String hasNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER));
Log.d(TAG, "hasNumber "+hasNumber);
mName.setText(name);
if(hasNumber.trim().equals("1")){
Log.d(TAG, "contact has telephone number");
//set name and number
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
mNumber.setText(phoneNumber);
}
}catch(Exception ex){
CharSequence text = context.getString(R.string.cannot_choose_contact);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if(cursor!= null && !cursor.isClosed()){
cursor.close();
}
}else{
CharSequence text = context.getString(R.string.cannot_choose_contact);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
I am getting: Failed to read row 0, column -1 from CursorWindow...
How do I get the phone number - am I trying to retrieve it from the right column?
Thanks in advance for your answers,
The detailed data for a contact is contained in a separate table from the main contact itself (see the Contacts API guide for more detail). Since you're sending an SMS, it might be more useful to only get the contacts who have a phone number associated, so you might as well go straight for the table which contains phone numbers. For the URI, I use:
CommonDataKinds.Phone.CONTENT_URI
Then you don't have to worry about HAS_PHONE_NUMBER. At a glance, the rest of your code looks right or very close. If you wanted to continue down your original path, you'd have to do a separate query on this table anyway, but provide it the ID of the contact that you initially found.
Use a CursorLoader to do queries. Always. If you continue to do queries on the UI thread, eventually you'll run into a situation where you hang the system and get an ANR.
You're requesting the user to pick contacts from the Contacts table, so you'll get back a URI that points to a contact in Contacts.
A trick for handling this is to strip the contact's LOOKUP_KEY from the returned URI using
Uri.getLastPathSegment(). Then search ContactsContract.Data for the LOOKUP_KEY and the
MIMETYPE value CommonDataKinds.Email.CONTENT_ITEM_TYPE. Based on your code, this would be:
mLookupKey = uri.getLastPathSegment();
String SELECTION = Data.LOOKUP_KEY + " = ? " +
" AND " +
Data.MIMETYPE + " = ?";
String[] selectionArgs = {
mLookupKey,
Email.CONTENT_ITEM_TYPE
};
...
I'm trying to allow a user to select a phone number from a contact using the contact picker. However, right now all the examples I see online show how you can select a contact, but I am hoping to have a second screen then pop up if that contact has multiple phone numbers so you can specify which one you want to select (the way that text message lets you do so when you select a contact).
My question is, do you have to gather all of the numbers and then ask the user to select a number, or is this functionality already built into Android? I'm hoping I just forgot a flag or something.
Alternatively, you can initially display the phone numbers associated with each contact in the Contact Picker and select one that way. Launch contact picker this way (note the different URI than my other answer):
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, REQUEST_PICK_CONTACT);
Then, in onActivityResult():
Uri result = data.getData();
Log.v(TAG, "Got a result: " + result.toString());
// get the phone number id from the Uri
String id = result.getLastPathSegment();
// query the phone numbers for the selected phone number id
Cursor c = getContentResolver().query(
Phone.CONTENT_URI, null,
Phone._ID + "=?",
new String[]{id}, null);
int phoneIdx = c.getColumnIndex(Phone.NUMBER);
if(c.getCount() == 1) { // contact has a single phone number
// get the only phone number
if(c.moveToFirst()) {
phone = c.getString(phoneIdx);
Log.v(TAG, "Got phone number: " + phone);
loadContactInfo(phone); // do something with the phone number
} else {
Log.w(TAG, "No results");
}
}
I was able to do this by creating a second dialog which shows all the phone numbers associated with a contact.
First, call this somewhere in your code:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, REQUEST_PICK_CONTACT);
Then in onActivityResult() use this to decide if the selected contact has multiple phone numbers, and display a dialog if so:
Uri result = data.getData();
Log.v(TAG, "Got a result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for phone numbers for the selected contact id
c = getContentResolver().query(
Phone.CONTENT_URI, null,
Phone.CONTACT_ID + "=?",
new String[]{id}, null);
int phoneIdx = c.getColumnIndex(Phone.NUMBER);
int phoneType = c.getColumnIndex(Phone.TYPE);
if(c.getCount() > 1) { // contact has multiple phone numbers
final CharSequence[] numbers = new CharSequence[c.getCount()];
int i=0;
if(c.moveToFirst()) {
while(!c.isAfterLast()) { // for each phone number, add it to the numbers array
String type = (String) Phone.getTypeLabel(this.getResources(), c.getInt(phoneType), ""); // insert a type string in front of the number
String number = type + ": " + c.getString(phoneIdx);
numbers[i++] = number;
c.moveToNext();
}
// build and show a simple dialog that allows the user to select a number
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.select_contact_phone_number_and_type);
builder.setItems(numbers, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
String number = (String) numbers[item];
int index = number.indexOf(":");
number = number.substring(index + 2);
loadContactInfo(number); // do something with the selected number
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(this);
alert.show();
} else Log.w(TAG, "No results");
} else if(c.getCount() == 1) {
// contact has a single phone number, so there's no need to display a second dialog
}
I know this is an old question but I hope it helps.
Just in case someone stumbles across this again.
Another alternative to the other answers is the library https://github.com/codinguser/android_contact_picker
Full Disclosure: I am the author of this library
it is simple explained on android developers reference:
https://developer.android.com/training/contacts-provider/modify-data.html#InsertEdit
and simple append code:
String phoneNumber = "+01 123 456 789";
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, phoneNumber);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CODE_ADD_PHONE_CONTACT);
}
if you needed activity result, you must listen to onActivityResult event on Activity by REQUEST_CODE_ADD_PHONE_CONTACT variable.