Monday, May 14, 2012

Code to import To, Cc, Bcc from user contact list in Android?


Step 1:
First of all you need to add code shown below in AndoidManifest.xml
<uses-permission android:name=”android.permission.READ_CONTACTS”></uses-permission>
with the help of which you will get access to the phone book of the device.
Step 2:
write the code shown below in your class
Set ACTIVITY_PICK_CONTACT = 1;
private void importContacts()
{
Intent intent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(intent,ACTIVITY_PICK_CONTACT);
}
Step 3:
Override function onActivityResult()
and add code shown below:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String strEmailIdOfContact;
int emailType = Email.TYPE_WORK;
String strContactName = null;
if (requestCode == ACTIVITY_PICK_CONTACT)
{
if(resultCode == RESULT_OK)
{
ContentResolver cr = this.getContentResolver();
Cursor cur = managedQuery(data.getData(), null, null, null, null);
if (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
strContactName = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ ” = ?”, new String[] { id }, null);
Cursor emails = cr.query(Email.CONTENT_URI, null,Email.CONTACT_ID + ” = ” + id, null, null);
if (emails.moveToNext()) {
strEmailIdOfContact = emails.getString(emails.getColumnIndex(Email.DATA));
emailType = emails.getInt(emails.getColumnIndex(Phone.TYPE));
if(_objClickedView == btnImportContactsTo)
{
String strGetTo = txtTo.getText().toString();
if(!strGetTo.equals(strEmailIdOfContact))
{
txtTo.setText(strGetTo+strEmailIdOfContact+”,”);
}
else
{
txtTo.setText(strEmailIdOfContact);
}
}
if(_objClickedView == btnImportContactsCc)
{
String strGetTo = txtCc.getText().toString();
if(!strGetTo.equals(strEmailIdOfContact))
{
txtCc.setText(strGetTo+strEmailIdOfContact+”,”);
}
else
{
txtCc.setText(strEmailIdOfContact);
}
}
if(_objClickedView == btnImportContactsBcc)
{
String strGetTo = txtBcc.getText().toString();
if(!strGetTo.equals(strEmailIdOfContact))
{
txtBcc.setText(strGetTo+strEmailIdOfContact+”,”);
}
else
{
txtBcc.setText(strEmailIdOfContact);
}
}
}
emails.close();
}
}
}// end of contact name cursor
}

No comments:

Post a Comment