Export The Contacts as Vcf File

Export the Contacts as VCF file

In your code, you wrote one function but from where is this function called? And what is the meaning of get(View view) function? This function is not being called so it can be removed.

I've edited my answer as per your requirements and tested it with 500 Contacts to save a single vCard file with 500 contacts in my sd card.

package com.vcard;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;

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

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf";
/**This Function For Vcard And here i take one Array List in Which i store every Vcard String of Every Conatact
* Here i take one Cursor and this cursor is not null and its count>0 than i repeat one loop up to cursor.getcount() means Up to number of phone contacts.
* And in Every Loop i can make vcard string and store in Array list which i declared as a Global.
* And in Every Loop i move cursor next and print log in logcat.
* */
getVcardString();

}
private void getVcardString() {
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{

get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}

}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}

}

public void get(Cursor cursor)
{

//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");

// Your Complex Code and you used function without loop so how can you get all Contacts Vcard.??

/* 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 out = new FileOutputStream(path);
out.write(VCard.toString().getBytes());
Log.d("Vcard", VCard);*/

FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);

String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
mFileOutputStream.write(vcardstring.toString().getBytes());

} catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

How to get all contacts and export to .vcf file?

Try out this. It's worked for me to create a .vcf file of all contact.

make sure all permission is given properly.

package com.vcard;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;

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

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf";
/**This Function For Vcard And here i take one Array List in Which i store every Vcard String of Every Conatact
* Here i take one Cursor and this cursor is not null and its count>0 than i repeat one loop up to cursor.getcount() means Up to number of phone contacts.
* And in Every Loop i can make vcard string and store in Array list which i declared as a Global.
* And in Every Loop i move cursor next and print log in logcat.
* */
getVcardString();

}
private void getVcardString() {
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{

get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}

}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}

}

public void get(Cursor cursor)
{
//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");

FileInputStream fis = fd.createInputStream();
byte[] buf = readBytes(fis);
String vcardstring= new String(buf);
vCard.add(vcardstring);

String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
mFileOutputStream.write(vcardstring.toString().getBytes());

} catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];

// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}

// and then we can return your byte array.
return byteBuffer.toByteArray();
}
}

How can i export contacts to .vcf file

Try belowpost for export contacts in android phone:

Import/Export to VCard format programmatically using android OS 2.0 API level 5

Extract contact list in vcf format

Thanks!

Extract contact list in vcf format

This may be helpful to you. Try this with your need -

package com.vcard;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;

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

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf";
/**This Function For Vcard And here i take one Array List in Which i store every Vcard String of Every Conatact
* Here i take one Cursor and this cursor is not null and its count>0 than i repeat one loop up to cursor.getcount() means Up to number of phone contacts.
* And in Every Loop i can make vcard string and store in Array list which i declared as a Global.
* And in Every Loop i move cursor next and print log in logcat.
* */
getVcardString();

}
private void getVcardString() {
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{

get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}

}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}

}

public void get(Cursor cursor)
{
//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");

// Your Complex Code and you used function without loop so how can you get all Contacts Vcard.??
/* 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 out = new FileOutputStream(path);
out.write(VCard.toString().getBytes());
Log.d("Vcard", VCard);*/

FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);

String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
mFileOutputStream.write(vcardstring.toString().getBytes());

} catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

How can I create .vcf file for a single contact?

See the first line in the below code block. Here I am creating a new vFile everytime, this method will be called.So each contact will be saved in different files.

public void get(Cursor cursor)
{
vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf";

//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");

// Your Complex Code and you used function without loop so how can you get all Contacts Vcard.??

/* 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 out = new FileOutputStream(path);
out.write(VCard.toString().getBytes());
Log.d("Vcard", VCard);*/

FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);

String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
mFileOutputStream.write(vcardstring.toString().getBytes());

} catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

Export iPhone contacts to .vcf file programmatically

The general pieces you will need are:

  1. The Contacts framework for accessing the phone's contacts.
  2. The ContactsUI framework to use the built-in view controllers for accessing contacts.
  3. Use CNContactVCardSerialization.dataWithContacts to encode CNContact data to VCard format.
  4. Write the data to a file using data.writeToURL.
  5. Upload the data to the server using NSURLSession.

Below is an example which answers the question of saving a contact to VCard format.

import Contacts

// Creating a mutable object to add to the contact
let contact = CNMutableContact()

contact.imageData = NSData() // The profile picture as a NSData object

contact.givenName = "John"
contact.familyName = "Appleseed"

let homeEmail = CNLabeledValue(label:CNLabelHome, value:"john@example.com")
let workEmail = CNLabeledValue(label:CNLabelWork, value:"j.appleseed@icloud.com")
contact.emailAddresses = [homeEmail, workEmail]

contact.phoneNumbers = [CNLabeledValue(
label:CNLabelPhoneNumberiPhone,
value:CNPhoneNumber(stringValue:"(408) 555-0126"))]

let homeAddress = CNMutablePostalAddress()
homeAddress.street = "1 Infinite Loop"
homeAddress.city = "Cupertino"
homeAddress.state = "CA"
homeAddress.postalCode = "95014"
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]

let birthday = NSDateComponents()
birthday.day = 1
birthday.month = 4
birthday.year = 1988 // You can omit the year value for a yearless birthday
contact.birthday = birthday

let data = try CNContactVCardSerialization.dataWithContacts([contact])

let s = String(data: data, encoding: NSUTF8StringEncoding)

if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first {

let fileURL = directoryURL.URLByAppendingPathComponent("john.appleseed").URLByAppendingPathExtension("vcf")

try data.writeToURL(fileURL, options: [.AtomicWrite])
}


Related Topics



Leave a reply



Submit