I managed to write add program that upon the user click a button, he will be able to retrieve a phone number that will fill an editText box. The problem is that if a contact has multiple numbers, it will always take the top most number.
I have been reading another thread, Getting Number from Contacts Picker, there is an answer, but I don't get it. As I am new to android programming,
I'll appreciate if anyone out there could give me step by step instructions.
First, you may need to query all contact in phone book.
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// Build adapter with contact entries
Cursor mCursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
//
// Bind mCursor to to your Listview
//
After that, when user select a contact in your list view, you make a second query to get label and number of that contact.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
mCursor.moveToPosition(position);
startManagingCursor(mCursor);
String contactID = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phoneNumCursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { contactID }, null);
phoneNumCursor.moveToFirst();
Vector<String> phoneTypeList = new Vector<String>();
Vector<String> phoneNumberList = new Vector<String>();
while (!phoneNumCursor.isAfterLast()){
int type = phoneNumCursor.getInt(phoneNumCursor.getColumnIndex(Phone.TYPE));
phoneTypeList.add(String.valueOf(Phone.getTypeLabel(getResources(),type,"")));
phoneNumberList.add(phoneNumCursor.getString(phoneNumCursor.getColumnIndex(Phone.NUMBER)));
phoneNumCursor.moveToNext();
}
//
// Feel free to show label and phone number of that contact. ^^
//
Updated:
Below is an example if you want to use Contact Picker.
private static final int CONTACT_PICKER_RESULT = 1001;
protected void startContactPicker(){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phoneNumber = "";
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
int phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()){
phoneNumber = cursor.getString(phoneIdx);
//
// this will go through all phoneNumber of selected contact.
//
cursor.moveToNext();
}
}
} catch (Exception e) {
} finally {
if (cursor != null) {
cursor.close();
}
numberView.setText(phoneNumber);
}
break;
}
}
}
Related
I want to pick a contact from phone book using intent and selected contact should also contain respective city and state (if saved by user).
Here is what I am trying for past few days:
private void accessContacts() {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
intent.setDataAndType(ContactsContract.Contacts.CONTENT_URI,
ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_CONTACT:
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
String[] projection = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
String name = null;
String phoneNumber = null;
String city = null;
String state = null;
Cursor c =
getActivity().getContentResolver().query(contactData, null, null, null, null);
if (c != null) {
if (c.moveToFirst()) {
int nameIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
name = c.getString(nameIdx);
phoneNumber = c.getString(phoneNumberIdx);
String id = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup._ID));
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
+ ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = getActivity().getContentResolver()
.query(ContactsContract.Data.CONTENT_URI,
null, addrWhere, addrWhereParams, null);
if (addrCur.moveToFirst()) {
city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
}
addrCur.close();
}
c.close();
}
if (name == null) {
name = "No Name";
}
if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() < 10) {
handleAddConnectionError(getContext().getString(R.string.invalid_phone_number));
return;
}
Phonenumber.PhoneNumber number =
Utils.validateMobileNumber2(phoneNumber, Device.getCountryCode(getActivity()));
if (number == null) {
handleAddConnectionError(getContext().getString(R.string.invalid_phone_number));
return;
}
this.moveToCategoryPage(name, String.valueOf(number.getNationalNumber()),
Utils.getCountryCodeWithPlusSign(number), false, null,
city, state);
}
break;
}
}
While removing/changing this:
intent.setDataAndType(ContactsContract.Contacts.CONTENT_URI,
ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
it throws exception.
How can I get saved address from pick intent?
There's one big bug that I can see here:
String id = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup._ID));
You shouldn't use PhoneLookup.XXX columns when querying over Phone.CONTENT_URI, this code actually returns the Phone._ID column instead (because both have the same const string name), which is NOT a contactID, it is a specific phone's ID (or a Data._ID).
You also can't access columns from a cursor that you didn't specify in your projection.
So change you projection to:
String[] projection = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
};
and replace that line with:
Long contactId = c.getLong(2);
Another thing you can do is to simplify your second query by querying over StructuredPostal.CONTENT_URI like this:
String addrWhere = StructuredPostal.CONTACT_ID + " = " + contactId;
Cursor addrCur = getActivity().getContentResolver().query(StructuredPostal.CONTENT_URI, null, addrWhere, null, null);
Please note that unlike your first query for the Phone.NUMBER info, you app needs READ_CONTACTS permission to do the second query for the address, this is because you ask for a phone-picker intent which grants your app a temp. permission to access the picked phone number only from the contacts API, anything other then that requires permission.
So i've been trying to add contact to a edittext,i've used Onclickevent to invoke contacts and then once a contact has been selected,it should be written to edittext,but i'm not able to do that,below is my Onactivity result,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String name = "";
try {
Uri result = data.getData();
//writeToFile("uri" +result);
String id = result.getLastPathSegment();
// query for name
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id },
null);
if (cursor != null && cursor.moveToFirst())
{
int phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
writeToFile("ifcursor" +phoneIdx+nameIdx);
name = cursor.getString(nameIdx);
}
} catch (Exception e) {
//Log.e(DEBUG_TAG, "Failed to get name", e);
} finally {
if (cursor != null) {
cursor.close();
}
// phNo = (EditText) findViewById(R.id.phone_number);
phNo.setText(name);
if (name.length() == 0) {
Toast.makeText(getApplicationContext(),"Name not found for contact.",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
//Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
any help would be deeply appreciated,it stucks on "name not found"
Try this one
#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.DISPLAY_NAME);
String number = cursor.getString(column);
phNo.setText(number );
// Do something with the phone number...
}
}
}
If you need the user to pick a contact with a phone number, you should call the following intent:
Intent i = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
Then you can handle the response in onActivityResult like so:
Uri result = data.getData();
// because we asked for a Phone.CONTENT_URI picker, we'll get a uri for a Phone._ID entry
String id = result.getLastPathSegment();
String[] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER };
String selection = Phone._ID + "=" + id;
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, projection, selection,null, null);
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(0);
String number = cursor.getString(1);
Log.d("MyActivity", "got name=" + name + ", phone=" + number);
}
if (cursor != null) {
cursor.close();
}
I have used an intent of contact picker. I am getting the data of contact through the intent. By that that intent I am fetching the name, number of the contact person.
When I tried to fetch an email id of contact it only shows the number of the contact instead of an email id. Also for last name of contact it shows always null though the last is been set to the contact.
Code:
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null ;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int contactIdIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int emailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
int lastNameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
mOrganizerPhone = cursor.getString(phoneIndex);
mOraganizerName = cursor.getString(nameIndex);
mOrganizersId = cursor.getString(contactIdIndex);
mOrganizersEmail = cursor.getString(emailIndex);
mOrganizersLastName = cursor.getString(lastNameIndex);
Toast.makeText(PlanEventActivity.this,name+" "+phoneNo,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Thank you..
With "id", you can get the email address like this, this is an example:
public class CustomerForm extends Activity {
private final static int CONTACT_PICKER = 1;
private EditText txtMailContacto;
private EditText txtNombreContacto;
private EditText txtTelefono;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_form);
txtMailContacto = (EditText) findViewById(R.id.txtMailContacto);
txtTelefono = (EditText) findViewById(R.id.txtTelefono);
txtNombreContacto = (EditText) findViewById(R.id.txtNombreContacto);
}
public void pickContact(View v)
{
Intent contactPickerIntent =
new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be using multiple startActivityForReslut
switch (requestCode) {
case CONTACT_PICKER:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
try {
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cur = getContentResolver().query(uri, null, null, null, null);
cur.moveToFirst();
// column index of the contact ID
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// column index of the contact name
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
txtNombreContacto.setText(name); //print data
// column index of the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
txtTelefono.setText(phone); //print data
}
pCur.close();
// column index of the email
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
txtMailContacto.setText(email); //print data
}
emailCur.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want user to select a number from calllog and that number get selected and come in the activity. So I created custom calllog list. I used this code but it is not showing the call log list in right order
first thing it is showing the callhistory of the first number fully that it gets in the calllog list
second I wnt to show the name also, I tried a lot but I am not able to do
Can anyone tell what amendments i make in this code to make it right
The code I used is:
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME };
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = this.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(this);
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
You can add the Contact Numbers in a Set, which will prevent adding duplicate contact numbers. Then add the Set's data to listview as you want.
Set<String> setNumbers = new HashSet<String>();
String callNumber = cursor.getString(cursor.getColumnIndex(
android.provider.CallLog.Calls.NUMBER));
setNumbers.add(callNumber);
Hope this helps.
For saving numbers without duplicates, as MysticMagic suggested, use 'Set' as per the link given in the comment.
For getting the contact name from the phone number, use code :
(Reference)
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;
}
Also refer here for another method to fetch name in phone call history
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
Finally this is the code that worked with the help of MysticMagic and Nishanthi Grashia
Set setA;
setA = new HashSet();
public void getCallLog() {
try {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
final Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"), projection,
selection, selectionArgs, sortOrder);
if (cursor != null) {
// Loop through the call log.
while (cursor.moveToNext()) {
// Common Call Log Items
String callNumber = cursor
.getString(cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
setA.add(callNumber);
}
generateList();
}
} catch (Exception e) {
}
}
#SuppressLint("NewApi")
private void generateList() {
// TODO Auto-generated method stub
try {
Object[] calllist = new String[setA.size()];
calllist = setA.toArray();
String scalllist[] = Arrays.copyOf(calllist, calllist.length,
String[].class);
for (int i = 0; i < scalllist.length; i++) {
scalllist[i] = scalllist[i] + " "
+ getContactName(this, scalllist[i]);
}
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog1);
d.setTitle("Choose from Call Log...");
final ListView lv1 = (ListView) d.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
scalllist);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String clickednumber[] = (lv1.getItemAtPosition(arg2)
.toString()).split(" ");
usernumber.setText(clickednumber[0]);
try {
username.setText(clickednumber[1]);
} catch (ArrayIndexOutOfBoundsException e) {
username.setText(" ");
}
d.dismiss();
}
});
d.show();
} catch (Exception e) {
}
}
private String getContactName(Context context, String number) {
String name = null;
try {
// 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));
} else {
name = " ";
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
I am trying to create a Custom Contact app which displays only those contacts that have Contact Number. First of all, is there any automated way to do it? Suppose not, then I am trying to search a contact by its name e.g. Rohan.
Here is the code :-
Cursor photoCursor = getContentResolver().query(
android.provider.ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.DISPLAY_NAME },
ContactsContract.Contacts.DISPLAY_NAME + " = ?",
new String[]{"Rohan"}, null);
photoCursor.moveToFirst();
while (photoCursor.moveToNext()) {
Log.d("Photo Thumbnail", "" + photoCursor.getString(1));
}
Although the contact exists, I am not getting any Log, if I remove Selection & Selection Args I see Rohan in the log. What am I doing wrong?
Simple Solution for Searching Partial Display Name.
ContentResolver contentResolver = getCurrentActivity().getContentResolver();
String whereString = "display_name LIKE ?";
String[] whereParams = new String[]{ "%" + searchText + "%" };
Cursor contactCursor = contentResolver.query(
ContactsContract.Data.CONTENT_URI,
null,
whereString,
whereParams,
null );
while( contactCursor.moveToNext() ) {
int contactId = getIntFromCursor( contactCursor, ContactsContract.Data.CONTACT_ID );
Log.d( "Contact ID", contactId)
}
contactCursor.close();
I did it by using the following code
Cursor cursor = getContentResolver().query(
android.provider.ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID },
ContactsContract.Contacts.HAS_PHONE_NUMBER, null,
ContactsContract.Contacts.DISPLAY_NAME);
This cursor gives all the contacts that have any phone number and then i save the unique ID in an ArrayList like this
cursor.moveToFirst();
while (cursor.moveToNext()) {
contactsID.add(cursor.getString(2));
}
then on selecting the contact i find the contact numbers using this
Cursor cursor = getContentResolver()
.query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { contactsID.get(position) }, null);
contactNumbers = new ArrayList<String>();
while (cursor.moveToNext()) {
contactNumbers.add(cursor.getString(0));
Log.d("number", cursor.getString(0));
}
Try this:
Cursor contactLookupCursor =
getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode("Rohan")),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER},
null,
null,
null);
try {
while (contactLookupCursor.moveToNext()) {
contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
contactNumber = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.NUMBER));
}
} finally {
contactLookupCursor.close();
}
It looks like you are trying to implement a screen that will allow the user to select a contact, and then select a phone number of that contact.
If that's the case, you can use a phone-picker intent instead:
Intent intent = Intent(Intent.ACTION_PICK);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER);
This will open the native Contacts app, and allow the user to select a contact, and a phone number.
You'll then receive the result in your app like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == RESULT_OK) {
// Get the URI and query the content provider for the phone number
Uri contactUri = data.getData();
String[] projection = new String[]{CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection,
null, null, null);
// If the cursor returned is valid, get the phone number
if (cursor != null && cursor.moveToFirst()) {
int numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberIndex);
// Do something with the phone number
...
}
}
}