Sarbjit Singh Sarbjit Singh - 1 month ago 8
Android Question

Get ContactId at the time of inserting a new contact programmatically to phone in android

I am trying to get contactId of newly added contact programmatically. Contact is being added successfully and fetches the contactID from ContentProviderResult[] but contactId which I am getting is not the correct one. I have also seen this and this answer but contactId is not the correct one. Here is my code

ArrayList<ContentProviderOperation> contentProviderOperation = new ArrayList<>();
......
......

ContentProviderResult[] results = getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation);
long contactId = ContentUris.parseId(results[0].uri);


I have also tried the below code:

ContentProviderResult[] results = getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation);
Uri myContactUri = results[0].uri;

int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
int contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash+1, length));


But the contactId I am getting here is not the correct one. Please Correct me if I am going something wrong. Thanks in advance.

Answer

After working regularly I have find a way to find out the correct contactId by the following code:

public static int getContactIDFromNumber(String contactNumber, Context context) {
        contactNumber = Uri.encode(contactNumber);
        int phoneContactID = new Random().nextInt();
        Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, contactNumber), new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
        while (contactLookupCursor.moveToNext()) {
            phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
        }
        contactLookupCursor.close();

        return phoneContactID;
    }

Pass the contactId of newly added contact that is present in an arrayList. I know this is not the correct way to find the contact. But it works for me.

Comments