Search code examples
androidandroid-contactsvcf-vcard

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


I have successfully created .vcf file for the all contacts from my android device. I have referred below link for doing so :

Export the Contacts as VCF file

and its working quite good. But, I need to convert a single contact to single .vcf file as per my requirement.

In this current code getting all the contacts using below lines :

cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

and then all contacts will be covered in .vcf file.

So, What is way that I can generate .vcf file for a single contact ?


Solution

  • 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();
            }
        }