AnilV
AnilV

Reputation: 179

Creating vCard file programmatically in android

I am using the following code to read contacts and create a vcard file.

            String lookupKey = cur.getString(cur.getColumnIndex(Contacts.LOOKUP_KEY));
            Uri uri=Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);


            try {
                fd = cr.openAssetFileDescriptor(uri, "r");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }       
            try {
                fis = fd.createInputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            byte[] buf = new byte[(int)fd.getDeclaredLength()];
            try {
                if (0 < fis.read(buf))
                {
                    vCard = new String(buf);
                    writer.write(vCard);
                    writer.write("\n");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

But while going through the list of contacts, I get the error:

ERROR/MemoryFile(284): MemoryFile.finalize() called while ashmem still open.

And my generated .vcf file is missing some contacts and also does not end properly.

Can someone please tell me what is wrong with my code.

Upvotes: 3

Views: 5726

Answers (2)

garmax1
garmax1

Reputation: 881

You need close stream fis

        try {
            fis = fd.createInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] buf = new byte[(int)fd.getDeclaredLength()];
        try {
            if (0 < fis.read(buf))
            {
                vCard = new String(buf);
                writer.write(vCard);
                writer.write("\n");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Close stream
        fis.close();

Upvotes: 1

kakopappa
kakopappa

Reputation: 5085

I had the same issue. I used a open source android-vcard jar to write the contacts to vcard.

Upvotes: 0

Related Questions