当"没有"从文件选择/图库中选择图像时,应用程序崩溃

Mik*_*s4u 0 java android

当我尝试选择一个图像时,filechooser会显示"相机"和"文件",如果我没有选择一个并点击它,它会崩溃吗?我试过几个答案,但我是webdev而不是android dev.救命!

这类似于在没有选择任何图像的情况下从图库返回时的应用程序崩溃

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Kap*_*l G 5

在进行计算之前,您还没有进行任何有resultCode针对性的检查onActivityResult.当你在没有选择图像的情况下回来时,resultCode是,RESULT_CANCELLED而你的data是null.发布任何操作data都将导致空指针异常

做如下 -

if (resultCode==RESULT_OK){
  // do stuff here that is the part of your try catch block
}
Run Code Online (Sandbox Code Playgroud)

当您尝试对不存在的数据执行data.getDataString()时,大多数代码都会崩溃.而且考虑到这是在你的尝试块之外,它永远不会被抓住和应用程序崩溃.

  • 有一个.它已接近尾声,可能要迟到,但有一个 (2认同)