当我尝试选择图像时,文件追踪器会显示“相机”。和'文件',如果我没有选择一个并点击,它会崩溃? 我试过几个答案,但我是webdev而不是android dev。救命啊!
这类似于app crashes when going back from gallery without selecting any image
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
try {
String file_path = mCameraPhotoPath.replace("file:","");
File file = new File(file_path);
size = file.length();
}catch (Exception e){
Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage());
}
if (data != null || mCameraPhotoPath != null) {
Integer count = 1;
ClipData images = null;
try {
images = data.getClipData();
}catch (Exception e) {
Log.e("Error!", e.getLocalizedMessage());
}
if (images == null && data != null && data.getDataString() != null) {
count = data.getDataString().length();
} else if (images != null) {
count = images.getItemCount();
}
Uri[] results = new Uri[count];
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (size != 0) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else if (data.getClipData() == null) {
results = new Uri[]{Uri.parse(data.getDataString())};
} else {
for (int i = 0; i < images.getItemCount(); i++) {
results[i] = images.getItemAt(i).getUri();
}
}
}
mUploadMessage.onReceiveValue(results);
mUploadMessage = null;
}
}
答案 0 :(得分:5)
在进行计算之前,您尚未在resultCode
进行任何onActivityResult
导向检查。当您在没有选择图像的情况下返回时,resultCode为RESULT_CANCELLED
且您的data
为空。发布data
上的任何操作将始终导致空指针异常
执行以下操作 -
if (resultCode==RESULT_OK){
// do stuff here that is the part of your try catch block
}
当您尝试对不存在的数据执行data.getDataString()时,大多数代码都会崩溃。并且考虑到这是在你的try块之外它永远不会被抓住并且应用程序崩溃。