Thursday, 7 June 2012

Export Contacts as a VCF file in Android


public class VCardActivity extends Activity {
Cursor cursor;
ArrayList<String> vCard;
String vfile;
static Context mContext;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = VCardActivity.this;
getVCF();
}

public static void getVCF() {
final String vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                  null, null, null);
phones.moveToFirst();
for (int i = 0; i < phones.getCount(); i++) {
String lookupKey = phones.getString(phones
.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_VCARD_URI,
                                                 lookupKey);
AssetFileDescriptor fd;
try {
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
String path = Environment.getExternalStorageDirectory()
.toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path,
true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
Log.d("Vcard", VCard);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}

Enjoy :-)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

9 comments:

  1. Great code. Thanks.
    I'm trying to figure out how to import as well.

    ReplyDelete
    Replies
    1. It works just fine. Actually i was trying to import them back can you help.

      Delete
  2. sir it is working in 2.3.3 but it is not working in 4.2 ... plz help

    ReplyDelete
  3. hello sir,
    i want to export call log in vcf file in sd card
    please give me code.

    ReplyDelete
  4. How to import contacts without using Intent ?

    ReplyDelete
  5. Every contact that has more than one phone number (a mobile and work number) are saved twice. And both of the numbers are in each duplicate contact, so they are correct, just duplicated. so pls help me out

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Great code. It does all the trick. But I'm still trying to make it work in 4.2... need help pls!

    ReplyDelete