简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM