2016-10-03 70 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);