2016-10-03 50 views
0

问题是当我尝试在Android 7.0上共享联系人时,我的应用程序崩溃。在Android 7.0上共享联系人

final ContentResolver resolver = context.getContentResolver(); 

      cursor = resolver.query(contactsUri, null, null, null, null); 
      String name = ""; 
      String contactLookupKey = ""; 
      if (cursor != null && cursor.moveToFirst()) { 
       name = cursor.getString(cursor.getColumnIndexOrThrow(
         ContactsContract.Contacts.DISPLAY_NAME)); 
       contactLookupKey = cursor.getString(cursor.getColumnIndexOrThrow(
         ContactsContract.Contacts.LOOKUP_KEY)); 
      } 

      name = name.replaceAll("[^0-9a-zA-Z]", "_"); 
      name = name + "_" + CONTACT_PREFIX; 
      Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, 
        contactLookupKey); 

      File storageDir = new File(Environment.getExternalStorageDirectory(), "contacts"); 
      if (!storageDir.exists()) { 
       storageDir.mkdir(); 
      } 
      File vCardFile = File.createTempFile(name, ".vcf", storageDir); 

      if (!vCardFile.exists()) { 
       vCardFile.createNewFile(); 
      } 
      fileOutputStream = new FileOutputStream(vCardFile); 

      AssetFileDescriptor 
        fd = resolver.openAssetFileDescriptor(uri, "r"); 

      fis = fd.createInputStream(); 

      final byte[] buf = new byte[(int) fd.getDeclaredLength()]; 

fd.getDeclaredLength() - return "-1" and app crash? 

什么可能是问题?

+0

作品与 最后字节[] BUF =新的字节[1024]; 所以,这是没有问题的原因,当我打开fd对象在debuger中,他的长度是-1 ...和联系人是空的,所以问题在.openAssetFileDescriptor(uri,“r”) – JRdev

回答

1

解/ 代替:

final byte[] buf = new byte[(int) fd.getDeclaredLength()]; 

使用:

byte[] buf; 

if (fd.getDeclaredLength() != AssetFileDescriptor.UNKNOWN_LENGTH) { 
    buf = new byte[(int) fd.getDeclaredLength()]; 
} else { 
    buf = new byte[fis.available()]; 
} 
fis.read(buf);