以下代码用于将联系人备份为vcf文件。 这适用于api 23以下的设备,但在更高的api中我得到java.lang.NegativeArraySizeException:-1。任何想法为什么? 感谢
这是完整的代码和错误日志
private void getVcardString() throws IOException {
// TODO Auto-generated method stub
//ProgressBar pro = (ProgressBar)findViewById(R.id.pb);
try {
// ProgressBar pro = (ProgressBar) findViewById(R.id.pb1);
vCard = new ArrayList<String>(); // Its global....
cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1",
null, null, null);
if (cursor != null && cursor.getCount() > 0) {
int i;
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
cursor.moveToFirst();
for (i = 0; i < cursor.getCount(); i++) {
get(cursor);
Log.d("TAG", "Contact " + (i + 1) + "VcF String is" + vCard.get(i));
cursor.moveToNext();
mFileOutputStream.write(vCard.get(i).toString().getBytes());
}
mFileOutputStream.close();
cursor.close();
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
tx.setText("");
pro.setVisibility(View.GONE);
btn3.setVisibility(View.VISIBLE);
tx1.setVisibility(View.VISIBLE);
Toast toast = Toast.makeText(getApplicationContext(), R.string.backupdone, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 90);
toast.show();
}
});
} else {
Log.d("TAG", "No Contacts in Your Phone");
}
}catch ( Exception e){
e.printStackTrace();
}}
private void get(Cursor cursor2) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring = new String(buf);
vCard.add(vcardstring);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
错误记录
07-03 00:20:55.796 9500-10477/com.HEbackup W/System.err:
java.lang.NegativeArraySizeException: -1
07-03 00:20:55.796 9500-10477/com.HEbackup W/System.err: at
app.HEbackup.cbackup$1.get(cbackup.java:212)
07-03 00:20:55.796 9500-10477/com.HEbackup W/System.err: at
app.HEbackup.cbackup$1.getVcardString(cbackup.java:172)
07-03 00:20:55.796 9500-10477/com.HEbackup W/System.err: at
app.HEbackup.cbackup$1.access$000(cbackup.java:120)
07-03 00:20:55.797 9500-10477/com.HEbackup W/System.err: at
app.HEbackup.cbackup$1$1.run(cbackup.java:144)
07-03 00:20:55.797 9500-10477/com.HEbackup W/System.err: at
java.lang.Thread.run(Thread.java:761)
答案 0 :(得分:2)
fd.getDeclaredLength()
返回-1
,您尝试用它来创建数组。由于长度为负的数组不存在,因此您获得NegativeArraySizeException
。
由于看起来指定的资产没有使用BufferedReader
(以及InputStreamReader
)处理内容的预定义长度,因此转换为String
将是正确的解决方案。
答案 1 :(得分:0)
django.middleware.http.ConditionalGetMiddleware