I am trying to create a button that opens up contacts and then when you select one contact it fetches the email and adds it to a field in the application.
I've been using the solution found here:
How to call Android contacts list AND Select one phone number from its details screen?
I have changed the code to select the email, but i still get the phone number.
The code is the following:
#Override
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.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.ADDRESS},
null, null, null);
if (c != null && c.moveToFirst()) {
long number = c.getLong(0);
String type = c.getString(1);
String mail = c.getString(2);
showSelectedNumber(type, number, mail);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(String number, long type, String email) {
Toast.makeText(this, type + ": " + number+ ": " + email, Toast.LENGTH_LONG).show();
}
EDIT:
The problem was on the initial query on the onClick call. I am posting the right function
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = null;
public void doLaunchContactPicker(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Email.CONTENT_TYPE);
startActivityForResult(intent, 1);
}
Sorry,I do not know why it still get the phone number. But , you can screen the results from contacts again by regular expression , if match to email address ,save and if not ,remove
I am sorry for my bad english!
Add a method like this:
private boolean checkMailAddress(String mailAddress){
final String MAIL_ADDR_REGEX = "([\\w-\\.\\\\+]+)#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
return mailAddress.matches(MAIL_ADDR_REGEX);
}
and I think that you should use "while" , not "if":
while(c != null && c.moveToNext()) {
long number = c.getLong(0);
String type = c.getString(1);
String mail = c.getString(2);
if(checkMailAddress(mail)){
showSelectedNumber(type, number, mail);
}
}
Related
I'm working on a Cordova app that needs to be able to get a list of phone numbers involved in a group text. I'm querying content://mms/[id]/addr for that. I'm testing on a Pixel 2 and for the MMS messages prior to March 10, 2018, this works fine. But for messages on or after that date, it fails (comes back as null). Is there a different address I should be querying? Any other ideas?
Using content://mms/ wil give you MMS conversation list and using content://mms-sms/conversations will give you both the first one or 2nd one you can try both if any of them doesn't work
so first you will have to get a list of MMS only using
ContentResolver contentResolver = getContentResolver();
final String[] projection = new String[]{"_id", "ct_t"};
Uri uri = Uri.parse("content://mms-sms/conversations");
Cursor query = contentResolver.query(uri, projection, null, null, null);
if (query.moveToFirst()) {
do {
String itemId = query.getString(query.getColumnIndex("_id"));
int getRowID = Integer.parseInt(itemId);
String string = query.getString(query.getColumnIndex("ct_t"));
if ("application/vnd.wap.multipart.related".equals(string)) {
// this item is MMS so get the number using function getAddressNumber and log it
Log.d("number","address/number:" + getAddressNumber(getRowID));
} else {
// item is sms do nothing
}
} while (query.moveToNext());
}
private String getAddressNumber(int id) {
String selectionAdd = new String("msg_id=" + id);
String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
Uri uriAddress = Uri.parse(uriStr);
Cursor cAdd = getContentResolver().query(uriAddress, null,
selectionAdd, null, null);
String name = null;
if (cAdd.moveToFirst()) {
do {
String number = cAdd.getString(cAdd.getColumnIndex("address"));
if (number != null) {
try {
Long.parseLong(number.replace("-", ""));
name = number;
} catch (NumberFormatException nfe) {
if (name == null) {
name = number;
}
}
}
} while (cAdd.moveToNext());
}
if (cAdd != null) {
cAdd.close();
}
return name;
}
if above function getAddressNumber doesn't work you can try this one as well with a little bit of changes
public static String getMMSAddress(Context context, String id) {
String addrSelection = "type=137 AND msg_id=" + id;
String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
Uri uriAddress = Uri.parse(uriStr);
String[] columns = { "address" };
Cursor cursor = context.getContentResolver().query(uriAddress, columns,
addrSelection, null, null);
String address = "";
String val;
if (cursor.moveToFirst()) {
do {
val = cursor.getString(cursor.getColumnIndex("address"));
if (val != null) {
address = val;
break;
}
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return address;
}
here is the defination for line
String addrSelection = "type=137 AND msg_id=" + id;
type constant come from the PduHeadersPduHeaders
class: 0x97 / 151 is PduHeaders.TO and 0x89 / 137 is PduHeaders.FROM you can change FROM or TO what you need.
if its still empty try below part and implement this in your code
Uri uriMms = Uri.parse("content://mms/");
final String[] projection = new String[]{"*"};
Cursor cursor = contentResolver.query(uriMms, projection, null, null, null);
String id = cursor.getString(cursor.getColumnIndex("_id"));
String selectionPart = "mid=" + id;
Uri uri = Uri.parse("content://mms/part");
Cursor cursor2 = getContentResolver().query(uri, null, selectionPart, null, null);
Here's how AOSP's (Android Open Source Project) messaging app does it:
Every message (SMS/ MMS) has a message ID represented as _ID in their respective tables
With this id pull the thread for the respective message
The threads table has a column called recipient_ids, this might be Space separated for group message, something like this:
123 456 789
Where 123 456 etc are the recipient ids.
Get address for respective recipient ids. Now this is a bit tricky, but AOSP uses the following uri: content://mms-sms/canonical-address
So the final method to get an array of addresses looks something likes this:
private fun getAddressFromRecipientId(spaceSepIds: String, context: Context): Array<String?> {
val singleCanonicalAddressUri = Uri.parse("content://mms-sms/canonical-address")
with(spaceSepIds.split(" ")) {
val addressArray: Array<String?> = arrayOfNulls(this.size)
this.forEachIndexed { index, address ->
if (!address.isEmpty()) {
val longId = address.toLong()
context.contentResolver.query(ContentUris.withAppendedId(singleCanonicalAddressUri, longId), null, null, null, null).use { cursor ->
if (cursor != null && cursor.moveToNext())
addressArray[index] = "${cursor.getString(0)} "
}
}
}
return addressArray
}
return arrayOf()
}
Hope this helps. Also the function is in kotlin but it's pretty easy to figure out what's happening there.
Also, you already have ids, so you can just call this method with either the space separated IDs or without them, the function works both ways.
I'm trying to get the Email address of a user I select in the contact list. I am able to get the ID, phone and name of the contact and by using the ID, I am trying to get the Email address using a new Cursor but am unable to get the details from the contact.
Below is the code I am using:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent aData) {
super.onActivityResult(requestCode, resultCode, aData);
if (requestCode == PICK_CONTACT && resultCode == Activity.RESULT_OK && aData != null) {
ContentResolver cr = getContentResolver();
String phoneNo = "";
String name = "";
String id = "";
String email = "";
Uri uri = aData.getData();
if (uri != null) {
Cursor cursor = cr.query(uri, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
}
cursor.close();
} else {
showDialog(getString(R.string.lbl_error_message_contact));
}
} else {
showDialog(getString(R.string.lbl_error_message_contact));
}
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) { // when it gets here, it just skips the while loop and jumps down to the to close the emailCur
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
}
emailCur.close();
mMedia.setLendersName(name);
mMedia.setPhoneNumber(phoneNo);
mMedia.setEmail(email);
}
}
Could it be that the ID may not be correct?
EDIT
One thing that is really weird is that when I select a contact and return back to the screen. The ID is very different to the ID I get when I run #Android Team's code which returns all the contacts with email addresses. What could be the reason behind this?
My thinking when I was trying to get the email address was that the ID's wont be different, but it seems it is the case.
when you getting device contact information you can add permission in manifest file..
<uses-permission android:name="android.permission.READ_CONTACTS"/>
then after used below method to get all the email id which device store in contact..
/**
* this method read device in contact name and email.
*/
public void getContact() {
Cursor cur = getActivity().getContentResolver().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));
Cursor cur1 = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
//to get the contact names
String name = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.e("Name :", name);
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email", email);
}
cur1.close();
}
}
}
check in log cat show all email id to be added in device.
I hope you know the Permission part and all, just add this code once you are allowed permission by user, and populate the email string in Edittext use it wherever you want
Account[] accounts = AccountManager.get(activityContext).getAccountsByType("com.google");
for (Account account : accounts) {
// if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
}
You might have to use this piece of code in activity to Populate the data, just an Add On
runOnUiThread(new Runnable() {
public void run() {
regEmail.setText(emailId);
}
});
I don't think some of you understood what I was trying to say, but this is the solution I found to get the Contact details of a selected contact by starting an intent to get the details from the Systems contact list.
Start the intent with the following intent to get the Name and Phone number:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
Once the contact is selected, it comes back into onActivityResult. Here is an example of getting the Name and Phone number from the response.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent aData) {
super.onActivityResult(requestCode, resultCode, aData);
if (requestCode == PICK_CONTACT && resultCode == Activity.RESULT_OK && aData != null) {
final String[] projection = new String[]{ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Email.TYPE};
ContentResolver cr = getContentResolver();
String phoneNo;
String name;
String lookUpKey = "";
String email;
Uri uri = aData.getData();
if (uri != null) {
// ****************************First we want to get the Lookup Key, Name and Phone number****************************
Cursor cursor = cr.query(uri, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
lookUpKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
mMedia.setLendersName(name);
mMedia.setPhoneNumber(phoneNo);
}
// ****************************Now we want to get the email address, if any from the contact****************************
// At this point, we use the Lookup key of the contact above, to get the email address (If any)
if (!TextUtils.isEmpty(lookUpKey)) {
//Do a query with the Lookup key to get the email details (Could possibly get more data as well, but I just needed the email address
cursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, ContactsContract.Data.LOOKUP_KEY + "=?", new String[]{lookUpKey}, null);
if (cursor != null) {
while (cursor.moveToNext()) {
// Get the index of the column for the email address here
final int contactEmailColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
while (!cursor.isAfterLast()) {
// Here is where we get the email address itself
email = cursor.getString(contactEmailColumnIndex);
// Set it where ever you need it.
mMedia.setEmail(email);
cursor.moveToNext();
}
}
// Dont forget to close the cursor once you done with it
cursor.close();
}
}
} else {
showDialog(getString(R.string.lbl_error_message_contact));
}
} else {
showDialog(getString(R.string.lbl_error_message_contact));
}
}
}
So i've created a simple launcher using this tutorial. I've created a few empty buttons that I intend to use to dial a number instantly when they are pressed.
By default, the buttons have no assigned number. I want the button to launch the default contacts application window when first pressed, so the user can select a contact's number to assign to the button. I'll then launch this through an intent.
I have no idea how to make the first part of this work (bringing up the contacts app, and then assigning details to the button). How do I make this work?
if I understand your question corectly you need to start an activity for result . You start your activity (contacts app ) by clicking a button then onActivityResult - > you get the data you want .
For example :
private static final int REQUEST_CONTACT = 1;
private static final int RESULT_OK = -1;
private static final int RESULT_CANCELED = 0;
private Uri mInfo;
private Context mContext;
Button startContactsApp = (Button)findViewByid(...);
startContactsApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() { // you need a thread because this operation takes plenty of time
#Override
public void run() {
Intent contactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
contactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // to display contacts who have phone number
startActivityForResult(contactIntent, REQUEST_CONTACT);
}
}).start();
}
});
The result:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CONTACT){
if(resultCode == RESULT_OK && data != null){
mInfo = data.getData();
String name = getContactNameAgenda(); // the name you need
String phone = getContactPhoneNumberAgenda(); //the number you need
Toast.makeText(mContext,"CONTACT ADDED !",Toast.LENGTH_SHORT).show();
}
else if (resultCode == RESULT_CANCELED){
Toast.makeText(getActivity(),"CANCELLED OR SOME ERROR OCCURRED !",Toast.LENGTH_SHORT).show();
}
}
Here you'll get the name and the phone number from that selected contact :
private String getContactNameAgenda(){
Cursor cursor = mContext.getContentResolver().query(mInfo, null,
null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
cursor.close();
return name;
}
private String getContactPhoneNumberAgenda(){
Cursor cursor = mContext.getContentResolver().query(mInfo, new String[]{ContactsContract.Contacts._ID},
null, null, null);
cursor.moveToFirst();
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
cursor.close();
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone._ID + " = ? AND " + // Phone._ID is for the database ; Phone.CONTACT_ID is for contact when you are not querying that table
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{id},
null);
cursorPhone.moveToFirst();
String number = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
cursorPhone.close();
return number;
}
I hope this will help you.
This question already has answers here:
Getting a Photo from a Contact
(9 answers)
Closed 8 months ago.
With my present code I am getting only the contact number. But I want to get contact's name and contact's photo path. Have tried many codes by googling, but I am not able to get it done. Tried this too, but got FileNotFoundException. Can someone please help me achieve that by adding code snippets to the below code?
public void getContact(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode == 1)
{
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 phoneNumber = c.getString(0);
int type = c.getInt(1);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}
This code traverses all contacts and gets their first name, last name and photo as a bitmap:
Cursor cursor = App
.getInstance()
.getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// get firstName & lastName
Cursor nameCur = App.getInstance().getContentResolver()
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ StructuredName.CONTACT_ID
+ " = ?",
new String[] {
StructuredName.CONTENT_ITEM_TYPE,
Long.valueOf(id).toString() }, null);
if (nameCur != null) {
if (nameCur.moveToFirst()) {
String displayName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (displayName == null) displayName = "";
String firstName = nameCur.getString(nameCur.getColumnIndex(StructuredName.GIVEN_NAME));
if (firstName == null) firstName = "";
Log.d("--> ", firstName.length()>0?firstName:displayName);
String middleName = nameCur.getString(nameCur.getColumnIndex(StructuredName.MIDDLE_NAME));
if (middleName == null) middleName = "";
String lastName = nameCur.getString(nameCur.getColumnIndex(StructuredName.FAMILY_NAME));
if (lastName == null) lastName = "";
lastName = middleName + (middleName.length()>0?" ":"") + lastName;
Log.d("--> ", lastName);
}
nameCur.close();
}
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(App.getContext().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(id)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("--> ", photo);
}
}
if (cursor != null) { cursor.close(); }
You also needs this permission: <uses-permission android:name="android.permission.READ_CONTACTS" />
Hope that helps!
This is the method am using to get contact photo, number and name but am dong this from a Fragment.
1 Set the permission in your manifest.
<uses-permission android:name="android.permission.READ_CONTACTS" />
2 Declare a constant:
private static final int REQUEST_CODE_PICK_CONTACT = 1;
3 In my app the user is required to choose a phone contact by clicking on a button. So in the onClick() method I do this:
contactChooserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACT);
}
});
4 Add the methods to retrieve photo, name, and number:
private String retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getActivity().getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.e(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getActivity().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));
phoneNumber = contactNumber;
}
cursorPhone.close();
Log.e(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}
//Retrieve name
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getActivity().getContentResolver().query(uriContact, null, null, null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number.
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
personName = contactName;
}
cursor.close();
Log.e(TAG, "Contact Name: " + contactName);
}
//Retrieve photo (this method gets a large photo, for thumbnail follow the link below)
public void retrieveContactPhoto() {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactID));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
try {
AssetFileDescriptor fd =
getActivity().getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
photoAsBitmap = BitmapFactory.decodeStream(fd.createInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
finally, in your onActivityForResult method, do this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if(requestCode == REQUEST_CODE_PICK_CONTACT && resultCode == Activity.RESULT_OK) {
Log.e(TAG, "Response: " + data.toString());
uriContact = data.getData();
personPhoneTextField.setText(retrieveContactNumber());
//the method retrieveContactNumber returns the contact number,
//so am displaying this number in my EditText after getting it.
//Make your other methods return data of
//their respective types (Bitmap for photo)
retrieveContactPhoto();
retrieveContactName();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
That's it.For Activities, take a look at this Android: Get Contact Details (ID, Name, Phone, Photo) on Github
i know how to get all contact on Android, but if i choose the contact i can't get the contact what i want. example : i have 4 contact
joe have phone number 7889 987;
erick have phone number 8792 871;
nona phone number 3653 872 and 2345 907;
rina phone number 8796 235;
if i choose joe, i get nona's phone number= 2345 907
i don't know what is the problem on my application.
this is my code
public void tambahPenerima ( View v ) {
Intent i = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(i, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
Cursor cursor = null;
String name = "";
String number = "";
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while(cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex((ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
if(cursor!=null) {
cursor.close();
}
Intent kirimPesan = new Intent();
kirimPesan.setClass(this, kirimPesan.class);
kirimPesan.putExtra("nama", name);
kirimPesan.putExtra("nomor", number);
kirimPesan.putExtra("chiper", chiper);
startActivity(kirimPesan);
}
}
Somebody please help me, I really need help.
Sorry for my poor english.
thanks ..
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor != null && cursor.moveToFirst()) {
while(cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex((ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
this may helps you to get specific contact Details
here name or number pass and get contact details wich you want
private String getContactName(Context context, String number) {
String name = null;
// 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));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}