Showing some contacts multiple times in my App from phone book - java

I'm getting same contact three or two times in my app this happening with some contacts not with every contacts. In my app everything is working as expected but when clicking on show contact from my it's shows three time same contact but in mobile phone contact stored only one time. I tried everything from my side but not able to solve this can any body please help me. Or is there any alternative way for same.
Here is my code:-
#Override
protected Integer doInBackground(Void... params) {
try {
db = new WhooshhDB(myContext);
this.list = new ArrayList<>();
ContentResolver cr = myContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactModel model = new ContactModel();
if (phoneNo.replaceAll("\\s", "").trim().length() > 7) {
model.name = name;
model.mobileNumber = phoneNo.replaceAll("\\s", "");
if (model.mobileNumber.contains("-")) {
model.mobileNumber = model.mobileNumber.replaceAll("-", "");
}
model.iconHexColor = AppConstant.getRandomSubscriptionHexColor(myContext);
if (!phoneNumber.equals(model.mobileNumber)) {
list.add(model);
}
}
Log.i("FetchContacts", "Name: " + name);
Log.i("FetchContacts", "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if (cur != null) {
cur.close();
}
return AppConstant.SUCCESS;
} catch (Exception ex) {
return null;
}
}

You're printing those "FetchContacts" logs for per contact per phone, so if a contact has multiple phones stored for her you'll see it printed multiple times (even if it's the same phone number).
If you have an app like Whatsapp installed, then almost always you'll see all phone number duplicated for each contact causing those logs to be printed more then once per contact.
Also, that's a slow and painful way of getting contacts w/ phones.
Instead you can simply query directly over Phones.CONTENT_URI and get all phones in the DB, and map them out into contacts by Contact-ID:
Map<String, List<String>> contacts = new HashMap<String, List<String>>();
String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor cur = cr.query(Phone.CONTENT_URI, projection, null, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0); // contact ID
String name = cur.getString(1); // contact name
String data = cur.getString(2); // the actual info, e.g. +1-212-555-1234
Log.d(TAG, "got " + id + ", " + name + ", " + data);
// add info to existing list if this contact-id was already found, or create a new list in case it's new
String key = id + " - " + name;
List<String> infos;
if (contacts.containsKey(key)) {
infos = contacts.get(key);
} else {
infos = new ArrayList<String>();
contacts.put(key, infos);
}
infos.add(data);
}
// contacts will now contain a mapping from id+name to a list of phones.
// you can enforce uniqueness of phones while adding them to the list as well.

Get rid of
while (cur != null && cur.moveToNext()) {
Change it to
if(cur.moveToFirst()){
list.clear();

Related

App gets hanged while trying to read contacts

I'm working on an app which reads the phone contacts and displays them in the form of list. I have to send message to selected contacts from the list. But the problem is that the app gets hanged if the mobile has more than 500 contacts. I don't get where the problem is..
I found this code on internet and implemented in my app. Contacts will be displayed but after taking so much time. Here is my code
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.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));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur =
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"=?",
new String[]{id}, null);
while (pCur.moveToNext()) {
int phoneType = pCur.getInt(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
switch (phoneType) {
case Phone.TYPE_MOBILE:
Log.e(name + "(mobile number)", phoneNumber);
break;
case Phone.TYPE_HOME:
Log.e(name + "(home number)", phoneNumber);
break;
case Phone.TYPE_WORK:
Log.e(name + "(work number)", phoneNumber);
break;
case Phone.TYPE_OTHER:
Log.e(name + "(other number)", phoneNumber);
break;
default:
break;
}
}
pCur.close();
}
} }
To read contacts -
private void fetchContacts() {
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));
if (name == null || name.equals(""))
name = phoneNumber;
if (Utils.notNull(phoneNumber)) {
phoneNumber = Utils.checkAndWrapMobileNumber(getApplicationContext(), phoneNumber);
allContacts.put(phoneNumber, name);
contactList.add(phoneNumber);
}
}
phones.close();
}
And better to use this code in AssyncTask so read in background thread.
Hope it will help you :)
it is due to heavy task in UI thread that blocks UI, Use AyncTask for this purpose.

Obtain matching contact email and phone from android phone

I have managed to extract contact details from the phone by using ContactContract example I found, but I noticed that most of the people on my phone has a unique id key associated to their emails and phone numbers separately. For example, Alan's contact detail is split up as following when I extract it out from database even though they are for the same person:
key name email phone
20121 Alan alan#gmail.com null
20133 Alan null 04xxxxxxxx
So how does the phone manage the association with all these different keys in the contact (I assume there must be a separate table for it)? Is there any way to obtain this association? Because I can not just try match the name as people can have exactly the same name, you have to keep them separated as how they are stored on your phone contact.
(Or the messed up situation is due to all apps are able to save contact related details into the same database on the phone?)
My code looks like following (I forgot where I get this code from, but getDetailedContactList function is returning a list of contact of the above problem):
public static String CONTACT_ID_URI = ContactsContract.Contacts._ID;
public static String DATA_CONTACT_ID_URI = ContactsContract.Data.CONTACT_ID;
public static String MIMETYPE_URI = ContactsContract.Data.MIMETYPE;
public static String EMAIL_URI = ContactsContract.CommonDataKinds.Email.DATA;
public static String PHONE_URI = ContactsContract.CommonDataKinds.Phone.DATA;
public static String NAME_URI = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ? ContactsContract.Data.DISPLAY_NAME_PRIMARY : ContactsContract.Data.DISPLAY_NAME;
public static String PICTURE_URI = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ? ContactsContract.Contacts.PHOTO_THUMBNAIL_URI : ContactsContract.Contacts.PHOTO_ID;
public static String MAIL_TYPE = ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
public static String PHONE_TYPE = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
public Cursor getContactCursor(String stringQuery, String sortOrder) {
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
Log.e(TAG, "ContactCursor search has started...");
Long t0 = System.currentTimeMillis();
Uri CONTENT_URI;
if (stringQuery == null)
CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
else
CONTENT_URI = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(stringQuery));
String[] PROJECTION = new String[]{
CONTACT_ID_URI,
NAME_URI,
PICTURE_URI
};
String SELECTION = NAME_URI + " NOT LIKE ?";
String[] SELECTION_ARGS = new String[]{"%" + "#" + "%"};
Cursor cursor = getContentResolver().query(CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, sortOrder);
Long t1 = System.currentTimeMillis();
Log.e(TAG, "ContactCursor finished in " + (t1 - t0) / 1000 + " secs");
Log.e(TAG, "ContactCursor found " + cursor.getCount() + " contacts");
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
return cursor;
}
public Cursor getContactDetailsCursor() {
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
Log.e(TAG, "ContactDetailsCursor search has started...");
Long t0 = System.currentTimeMillis();
String[] PROJECTION = new String[]{
DATA_CONTACT_ID_URI,
MIMETYPE_URI,
EMAIL_URI,
PHONE_URI
};
String SELECTION = NAME_URI + " NOT LIKE ?" + " AND " + "(" + MIMETYPE_URI + "=? " + " OR " + MIMETYPE_URI + "=? " + ")";
String[] SELECTION_ARGS = new String[]{"%" + "#" + "%", ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
Cursor cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
PROJECTION,
SELECTION,
SELECTION_ARGS,
null);
Long t1 = System.currentTimeMillis();
Log.e(TAG, "ContactDetailsCursor finished in " + (t1 - t0) / 1000 + " secs");
Log.e(TAG, "ContactDetailsCursor found " + cursor.getCount() + " contacts");
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
return cursor;
}
public List<ContactViewModel> getDetailedContactList(String queryString) {
/**
* First we fetch the contacts name and picture uri in alphabetical order for
* display purpose and store these data in HashMap.
*/
Cursor contactCursor = getContactCursor(queryString, NAME_URI);
if(contactCursor.getCount() == 0){
contactCursor.close();
return new ArrayList<>();
}
List<Integer> contactIds = new ArrayList<>();
if (contactCursor.moveToFirst()) {
do {
contactIds.add(contactCursor.getInt(contactCursor.getColumnIndex(CONTACT_ID_URI)));
} while (contactCursor.moveToNext());
}
HashMap<Integer, String> nameMap = new HashMap<>();
HashMap<Integer, String> pictureMap = new HashMap<>();
int idIdx = contactCursor.getColumnIndex(CONTACT_ID_URI);
int nameIdx = contactCursor.getColumnIndex(NAME_URI);
int pictureIdx = contactCursor.getColumnIndex(PICTURE_URI);
if (contactCursor.moveToFirst()) {
do {
nameMap.put(contactCursor.getInt(idIdx), contactCursor.getString(nameIdx));
pictureMap.put(contactCursor.getInt(idIdx), contactCursor.getString(pictureIdx));
} while (contactCursor.moveToNext());
}
/**
* Then we get the remaining contact information. Here email and phone
*/
Cursor detailsCursor = getContactDetailsCursor();
HashMap<Integer, String> emailMap = new HashMap<>();
HashMap<Integer, String> phoneMap = new HashMap<>();
idIdx = detailsCursor.getColumnIndex(DATA_CONTACT_ID_URI);
int mimeIdx = detailsCursor.getColumnIndex(MIMETYPE_URI);
int mailIdx = detailsCursor.getColumnIndex(EMAIL_URI);
int phoneIdx = detailsCursor.getColumnIndex(PHONE_URI);
String mailString;
String phoneString;
if (detailsCursor.moveToFirst()) {
do {
/**
* We forget all details which are not correlated with the contact list
*/
if (!contactIds.contains(detailsCursor.getInt(idIdx))) {
continue;
}
if(detailsCursor.getString(mimeIdx).equals(MAIL_TYPE)){
mailString = detailsCursor.getString(mailIdx);
/**
* We remove all double contact having the same email address
*/
if(!emailMap.containsValue(mailString.toLowerCase()))
emailMap.put(detailsCursor.getInt(idIdx), mailString.toLowerCase());
} else {
phoneString = detailsCursor.getString(phoneIdx);
phoneMap.put(detailsCursor.getInt(idIdx), phoneString);
}
} while (detailsCursor.moveToNext());
}
contactCursor.close();
detailsCursor.close();
/**
* Finally the contact list is build up
*/
List<ContactViewModel> contacts = new ArrayList<>();
Set<Integer> emailsKeySet = emailMap.keySet();
Set<Integer> phoneKeySet = phoneMap.keySet();
for (Integer key : contactIds) {
if( (!emailsKeySet.contains(key) && !phoneKeySet.contains(key))
|| (emailMap.get(key) == null && phoneMap.get(key) == null)
|| mContactDB.isContactExisted(key))
{
continue;
}
contacts.add(new ContactViewModel(key, nameMap.get(key), emailMap.get(key)));
}
return contacts;
}
Try below code to fetch contact number of specific person.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Phone.CONTENT_URI, null, Phone.DISPLAY_NAME + "=?", new String[]{contactName}, null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
do {
String number = cursor.getString(mCursor.getColumnIndex(Phone.NUMBER));
}while (cursor.moveToNext() );
}
Android recommends using content resolvers and content providers to provide nicely packaged data between applications. You should probably not go messing around with the database itself, and it was clearly not designed with that in mind (as your experience demonstrates).
Instead, you should use the content resolver to query the Android ContactsContract to find what you need. There is a class called ContactsContract.Contacts that sounds like the entry point for what you need. Each record returned by a query to the class represents a single contact.
See the Content Providers Developer Guide for further details.

Change contact picture programmatically

I have a picture, that is stored into the android phone. I want to be able to change the picture of a contact.
What I've done so far is launch the contact picker, have the user select a contact, and then I get the URI of the selected contact. From this contact, I can get the associated rawContact and I use this code.
Uri rawContactPhotoUri = Uri.withAppendedPath(
ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId),
RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
try {
AssetFileDescriptor fd =
getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "rw");
OutputStream os = fd.createOutputStream();
os.write(photo);
os.close();
fd.close();
} catch (IOException e) {
// Handle error cases.
}
The problem is, the AssetFIleDescriptor is always empty (when I call length on it, we always get -1).
I'm not asking for the entire solution, just some leads to follow that can help me to get that working. I cannot seem to find this problem already on StackOverflow, so any help would be appreciated.
EDIT
It's always when we ask for question that we find the solution.
I want to share it for other
So I gave up on android link and find another one :
http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/
The picture picker return the Uri of the selected contact, so with this you can get the Contact._ID of it :
// This is onActivityResult
final Uri uri = data.getData();
final Cursor cursor1 = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
final long contactId = cursor1.getLong(cursor1.getColumnIndex(Contacts._ID);
cursor1.close();
Then I had to get the RawContactId :
final Cursor cursor2 = getContentResolver().query(RawContacts.CONTENT_URI, null, RawContacts.Contact_ID + "=?", new String[] {String.valueOf(contactId)}, null);
cursor2.moveToFirst();
final long rawContactId = cursor2.getLong(cursor2.getColumnIndex(RawContacts._ID));
cursor2.close();
Then I had to get the Data._ID of the RawContacts (same way as above).
Then I used the ContentProviderOperations :
final ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(Data._ID, dataId),
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, byteArrayOfThePicture);
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
And this is working like charm. Hope it helps
String contactId = "10001"; // change it as your IDs
if (mBitmap != null) {
// Picture
try {
ByteArrayOutputStream image = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, image);
Uri rawContactUri = null;
Cursor rawContactCursor = managedQuery(
ContactsContract.RawContacts.CONTENT_URI,
new String[] {
ContactsContract.RawContacts._ID
},
ContactsContract.RawContacts.CONTACT_ID + " = " + contactId,
null,
null);
if (!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendPath("" + rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
ContentValues values = new ContentValues();
int photoRow = -1;
String where111 = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(rawContactUri) + " AND " + ContactsContract.Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = managedQuery(
ContactsContract.Data.CONTENT_URI,
null,
where111,
null,
null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID,
ContentUris.parseId(rawContactUri));
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
values.put(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
if (photoRow >= 0) {
getContentResolver().update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data._ID + " = " + photoRow, null);
} else {
getContentResolver().insert(
ContactsContract.Data.CONTENT_URI,
values);
}
} catch (Exception e) {
Log.e("!_##Image_Exception", e + "");
}
}
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("#####UPLOADERR", e + "");
}

Display one Contact name with multiple numbers

I am trying to retrieve contacts from my phone that has only numbers and put them into an arrayList, view them in lazy adapter and on click of name I would like show only numbers. I managed to get the list of contacts and numbers but the problem is when I have a contact with multiple numbers it just adds up into the list.
Something like for e.g
David +1 508 656 9043
David +1 403 604 7053
David +1 212 608 7053
Instead I would like to show only David in the list and when I click it should show all the three numbers.
I tried this:
void getContactNumbers()
{
ContentResolver cr = getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, sortOrder);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("contact", "...Contact Name ...." + name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext())
{
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("contact", "...Contact Name ...." + name + "...contact Number..." + phoneNo);
}
pCur.close();
}
}
}
}
How to solve this part?
Thanks!
Thanks Harshid. There was selection change instead of IN_VISIBLE_GROUP + " = '1'"; -
I added HAS_PHONE_NUMBER + " = '1'";
All contacts came up.. Hope the below code helps others!!
Thanks!
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID
};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = getContentResolver().query(uri, projection, selection, null, sortOrder);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String Sid = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("contact", "...Contact Name ...." + name);
// get the phone number
Cursor pCur = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
number = pCur.getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
}
cur.close();
You have to this way query and get contact with multiple number.
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] selectionArgs = null;
final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("contact", "...Contact Name ...." + name);
// get the phone number
Cursor pCur = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
number = pCur.getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
}
cur.close();
Try this code if getting error then put comment otherwise enjoy..

Get the caller id

I'm trying to make app which will log my incoming and outgoing calls and the problem is i can't seem to get working this code to return caller id(Like name and surname) but it allways returns "Unknown"
public String getname(String num,String nbc ){
String namer="";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
try {
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.i("",name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get 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));
System.out.println("phone" + phone);
if(phone==nbc||phone==num)
{
namer = name;
return namer;
}
}
pCur.close();
}
}
}
}
catch (Exception e) {
// TODO: handle exception
}
return namer;
}
It doesn't execute this(if(phone==nbc||phone==num)) part.
Can you please tell me what's wrong or another way to do this or at least point me in the right direction.
Use equals to compare Strings
if(phone.equals(nbc)||phone.equals(num))

Categories

Resources