In Android 7, getContentResolver().openAssetFileDescriptor(vCardUri, "r")
returns AssetFileDescriptor
having declaredLength as -1 returned by getDeclaredLength()
.
Trying to export the contacts as vcards into vcf file. The code I have tried is as follows
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] b = new byte[(int)fd.getDeclaredLength()];
fis.read(b);
The above code works perfectly in Android 6 or below.But when ran using Android 7, The line creating byte[] results in NegativeByteArraySizeException
as the declaredLength is -1.
When I debugged downloading the sources of Android 7, I observed the problem.
Any kind of health would be really appreciable.
With the help of @pskink, I found the following solve my problem.
where the readAsByteArray() is written using the code from Mihai Snippet.
Thank you @pskink
In your code you are you are using the openAssestFileDescriptor instead use the openFileDescriptor because openAssestFileDescriptor is use to read a file in your asset folder not the file Uri
replace this
with this
In Android Nougat :
fd.getDeclaredLength() return -1.
Check my answer here link.