Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a .vcf file from an object which contains contact detail and object is not in the phone book

I want to generate a .vcf file for an object which contains contact information like name, image, phone number, fax number, email id, address etc. This object is not added in the address book of the phone but it is stored in my application.

Once my .vcf file is generated I can send this vcard like this

Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("**generated.vcf**"), "text/x-vcard");
startActivity(i);

But I am not getting how to get this generated .vcf file?

like image 268
Shaista Naaz Avatar asked Dec 04 '12 11:12

Shaista Naaz


Video Answer


1 Answers

It's actually quite easy to generate a .vcf file. Have a look at VCF format - it's a simple text file. All you need to do is create text file and write info into it using the VCF fields. You'll end up with something like this:

Person p = getPerson();

File vcfFile = new File(this.getExternalFilesDir(null), "generated.vcf");
FileWriter fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
fw.write("VERSION:3.0\r\n");
fw.write("N:" + p.getSurname() + ";" + p.getFirstName() + "\r\n");
fw.write("FN:" + p.getFirstName() + " " + p.getSurname() + "\r\n");
fw.write("ORG:" + p.getCompanyName() + "\r\n");
fw.write("TITLE:" + p.getTitle() + "\r\n");
fw.write("TEL;TYPE=WORK,VOICE:" + p.getWorkPhone() + "\r\n");
fw.write("TEL;TYPE=HOME,VOICE:" + p.getHomePhone() + "\r\n");
fw.write("ADR;TYPE=WORK:;;" + p.getStreet() + ";" + p.getCity() + ";" + p.getState() + ";" + p.getPostcode() + ";" + p.getCountry() + "\r\n");
fw.write("EMAIL;TYPE=PREF,INTERNET:" + p.getEmailAddress() + "\r\n");
fw.write("END:VCARD\r\n");
fw.close();

Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(vcfFile), "text/x-vcard");
startActivity(i);

(Note that this code is to be placed inside an activity. If it's not in an activity, then replace this in front of getExternalFilesDir with an instance of Context.)

You can have more of fewer fields, as needed. If you have ,, ; or \ characters in field values, they need to be escaped with \; to put a newline character into a value, write \\n into the file (i.e. the file itself must contain \n, the second slash is for escaping the slash in the newline).

This code is quite crude, but it should get you started. Again, have a look at the format of VCF and go from there.

Update: Thanks to @Michael for pointing out mistakes in my original answers.

like image 108
Aleks G Avatar answered Oct 07 '22 16:10

Aleks G