To retrieve contact list with number in android - android

Hi i want to retrieve name and numbers from contact list in android ,am using following code, it will give me name but not number it gives null value for number
NOTE: am using android emulator
public void demo(){
String phoneNumber;
String [] item = new String[]{ People._ID,
People.NAME,
People.NUMBER};
Cursor cur = getContentResolver().query(People.CONTENT_URI ,item , null, null, null);
int phoneNumberIndex = cur.getColumnIndexOrThrow(People.NUMBER);
if (cur != null) {
Log.v("cur not null", "Cursor Not null");
if (cur.moveToNext()) {
Log.v("moveToNext", "Moved to first");
Log.v("moveToNext", "Cursor Moved to first and checking");
phoneNumber = cur.getString(phoneNumberIndex);
System.out.println("****** from_number "+phoneNumber +" *****************");
}
}
}

It gives null because u r trying to retrieve only one number.. this should work..
if (cur.moveToNext()) {
Log.v("moveToNext", "Moved to first");
Log.v("moveToNext", "Cursor Moved to first and checking");
while(cur.moveToNext())
{
phoneNumber = cur.getString(phoneNumberIndex);
System.out.println("****** from_number "+phoneNumber +" *****************");
}
}

Related

Method to return contacts phone number always returns null - Android [duplicate]

I am able to retrieve the contact ID, but then later I wish to separately retrieve the phone number based on the contact ID. The code below is returning a null result for the phone number. (I do wish later to retrieve the name and phone number together and populate a view, but I am just trying to get the phone number to work first).
In my onCreate I have this code
String phoneNum = getPhoneNumber(myID);
TextView phoneTextView = (TextView) findViewById(R.id.textViewPhone);
phoneTextView.setText(phoneNum);
This is the method for getPhoneNumber()
protected String getPhoneNumber(String id) {
ArrayList<String> phones = new ArrayList<String>();
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cursor.moveToNext()) {
phones.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursor.close();
String phoneNum;
phoneNum = phones.get(0);
return phoneNum;
}//end getPhoneNumber();
}
This produces the error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0, which I plan on creating some error handling for. But still, I am certain I have the ID from the previous code, so I don't know why the ArrayList returns null. If you would like to see that code, it is also in my onCreate:
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() != 0) {
int numContacts = cursor.getCount();
ArrayList<String> idList = new ArrayList<>();
Random rand = new Random();
int randomNum = rand.nextInt(numContacts);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
idList.add(id);
}
myID = idList.get(randomNum);
String myString = Integer.toString(randomNum);
TextView myTextView = (TextView) findViewById(R.id.textViewID);
myTextView.setText(myString);
if (myID != null) {
myTextView.setText(myID);
} else {
myTextView.setText("Try Again!");
}
} else {
Toast.makeText(getApplicationContext(), "Your have no contacts.", Toast.LENGTH_SHORT).show();
}
cursor.close();
// You can fetch the Contact Number and Email With Following Methods.
String phone = getPhoneNumber(ContactId);
String email = getEmail("" + ContactId);
private String getPhoneNumber(long id) {
String phone = null;
Cursor phonesCursor = null;
phonesCursor = queryPhoneNumbers(id);
if (phonesCursor == null || phonesCursor.getCount() == 0) {
// No valid number
//signalError();
return null;
} else if (phonesCursor.getCount() == 1) {
// only one number, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} else {
phonesCursor.moveToPosition(-1);
while (phonesCursor.moveToNext()) {
// Found super primary, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
}
return phone;
}
private Cursor queryPhoneNumbers(long contactId) {
ContentResolver cr = getContentResolver();
Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
contactId);
Uri dataUri = Uri.withAppendedPath(baseUri,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
Cursor c = cr.query(dataUri, new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY, ContactsContract.RawContacts.ACCOUNT_TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL},
ContactsContract.Data.MIMETYPE + "=?",
new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, null);
if (c != null && c.moveToFirst()) {
return c;
}
return null;
}
private String getEmail(String id) {
String email = "";
ContentResolver cr = getContentResolver();
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
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
return email;
}
I have not been able to successfully retrieve code based on the Contact ID - but this post gave me a clue: Retrieving a phone number with ContactsContract in Android - function doesn't work
I have altered my original code to query on DISPLAY_NAME instead and things are working now. Here is the method I am using to retrieve the phone number:
private String retrieveContactNumber(String contactName) {
Log.d(TAG, "Contact Name: " + contactName);
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactName},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}

Fetch complete contact detail from ContactsContract.Profile

I am looking to fetch complete contact detail of the owner (me profile - e.g. in Nexus). I found ContactsContract.Profile API which is available for API v14+.
I am successfully able to get display name, corresponding to which i further require contact number. To do all this, i am using following code
private void getSelfSimNumber() {
String displayName = null;
try {
Cursor c = this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, null, null, null,
null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
displayName = c.getString(c
.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME));
if (Integer
.parseInt(c.getString(c
.getColumnIndex(ContactsContract.Profile.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " = ?", new String[] { displayName },
null);
while (pCur.moveToNext()) {
String ret = c.getString(0);
String ret1 = c.getString(1);
}
pCur.close();
}
}
c.close();
} catch (Exception e) {
}
}
The problem is I am unable to fetch contact number of "me" profile. If, suppose, I have total 3 contacts (including "me" profile) then total contacts available i am getting is only 2. The system is perhaps not considering "me" profile as a contact.
How to solve this problem and fetch contact number of "me" profile?
Thanks

Fetching Phone Number from Contacts based on Name Android

I am developing an application, where I need to fetch the phone number from the contacts corresponding to the name provided. I have tried many codes but none of them seem to work.
Here is the code I'm currently using now
public static String getContactPhoneNumber(Context context, String contactName, int type) {
String phoneNumber = null;
String[] whereArgs = new String[] { contactName, String.valueOf(type) };
Log.d(TAG, String.valueOf(contactName));
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.Contacts.DISPLAY_NAME + " = ? and "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", whereArgs, null);
int phoneNumberIndex = cursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
Log.d(TAG, String.valueOf(cursor.getCount()));
if (cursor != null) {
Log.v(TAG, "Cursor Not null");
try {
if (cursor.moveToNext()) {
Log.v(TAG, "Moved to first");
Log.v(TAG, "Cursor Moved to first and checking");
phoneNumber = cursor.getString(phoneNumberIndex);
}
} finally {
Log.v(TAG, "In finally");
cursor.close();
}
}
Log.v(TAG, "Returning phone number");
return phoneNumber;
}
On passing Contact Name (say: John Doe) and type (2 which is int value for Mobile Type), the phone number returned is null even though the contact "John Doe" exists in my contact list.
Please help!!!
Try this
instead of ContactsContract.CommonDataKinds.Phone.CONTENT_URI Pass
ContactsContract.Contacts.CONTENT_URI parameter to query method.

Querying the Contacts Database for phone number and handling multiple numbers

I want to query the Contacts Database for phone number and if the selected contact has multiple numbers, I display the available numbers for the user to select one of them.
I have code in place that would pick up the default number of the selected contact.
Cursor cursor = null;
String phoneNumber = "";
try
{
Uri result = data.getData();
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int pNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
// let's just get the first email
if (cursor.moveToFirst())
{
phoneNumber = cursor.getString(pNumberIdx);
}
}
catch (Exception e)
{
}
finally
{
if (cursor != null)
{
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.pNumber);
emailEntry.setText(phoneNumber);
if (phoneNumber.length() == 0)
{
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
}

using the contacts manager in android

i have an app which shows the received messages as a Toast through a BroadcastReceiver. I am presently using the SmsMessage.getOriginatingAddress() method which gives me the number of the sender, how can modify it to get the corresponding name of the sender if stored in the contacts?
You will need to query the contacts for the rest of the data.
First query for the contacts id using the phone number.
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, address),
new String[] { Contacts.Phones.PERSON_ID }, null, null, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
Long id = Long.valueOf(cursor.getLong(0));
if (Log.DEBUG) Log.v("Found person: " + id);
return (String.valueOf(id));
}
} finally {
cursor.close();
}
}
Then query for the Contacts name with the id from the first query.
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(Contacts.People.CONTENT_URI, id),
new String[] { PeopleColumns.DISPLAY_NAME }, null, null, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String name = cursor.getString(0);
if (Log.DEBUG) Log.v("Contact Display Name: " + name);
return name;
}
} finally {
cursor.close();
}
}
You may be able to combine these two queries somehow.

Categories

Resources