over 11 years ago
We can get a contact information for any contact from contact list of an Android Device easily. For this follow the steps below:
Write the permission to read Contact's data into your AndroidManifest.xml
Write the below code within your activity from where you want to perform action.
Also in your Activity, write the below code inside the onActivityResult method to listen for the result of step 2.
- if(resultCode==RESULT_OK && requestCode==1001)
- {
- String ContactInfo = null;
- Uri uriOfPhoneNumberRecord = data.getData();
- String idOfPhoneRecord = uriOfPhoneNumberRecord.getLastPathSegment();
- Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{idOfPhoneRecord}, null);
- if(cursor != null) {
- if(cursor.getCount() > 0) {
- cursor.moveToFirst();
- String formattedPhoneNumber = cursor.getString( cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA) );
- String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
- StringBuffer s=new StringBuffer(formattedPhoneNumber);
- for(int j=0;j<s.length();j++){
- if(s.charAt(j)=='-')
- {
- s.replace(j, j+1, "");
- }
- }
- ContactInfo = "Contact:\n".concat(contactName.concat("\n"+s.toString()));
- Log.d("Varta", String.format("The selected phone number is: %s", ContactInfo));
- }
- cursor.close();
- }
- }
if(resultCode==RESULT_OK && requestCode==1001) { String ContactInfo = null; Uri uriOfPhoneNumberRecord = data.getData(); String idOfPhoneRecord = uriOfPhoneNumberRecord.getLastPathSegment(); Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{idOfPhoneRecord}, null); if(cursor != null) { if(cursor.getCount() > 0) { cursor.moveToFirst(); String formattedPhoneNumber = cursor.getString( cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA) ); String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); StringBuffer s=new StringBuffer(formattedPhoneNumber); for(int j=0;j<s.length();j++){ if(s.charAt(j)=='-') { s.replace(j, j+1, ""); } } ContactInfo = "Contact:\n".concat(contactName.concat("\n"+s.toString())); Log.d("Varta", String.format("The selected phone number is: %s", ContactInfo)); } cursor.close(); } }
Please feel free to share the experiences you had while getting contact information from contact list in your code as this will help other people who read the post.
0 Comment(s)