java - 当我尝试访问应用程序的 Intent 数据时,为什么它会崩溃?

标签 java android image crash thumbnails

我正在开发一个Android应用程序,当我按下按钮拍照时,它会不断崩溃,然后应该将图片保存到文件夹中并在应用程序中显示缩略图,但是一旦我拍照,应用程序就会崩溃,但仍将照片保存在所需的文件夹中。在我开始实现应用程序的照片保存部分之前,显示缩略图就可以工作了。

应用程序一旦到达此代码块就会崩溃(onActivityResult 重写函数):

        if(data.getData() == null) {
            thumbnail.add((Bitmap)data.getExtras().get("data"));
        }
        if(thumbnail.get(0) != null && thumbnail.size() > 0)
        {
            for(int i=0; i < thumbnail.size();i++){
                //Toast.makeText(getApplicationContext(), Integer.toString(thumbnail.size()), Toast.LENGTH_SHORT).show();
                createPhotoThumbnail(thumbnail);
            }
        }

这是相机调度 Intent 函数:

private void dispatchCameraIntent(){
    Intent takePicIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    if (takePicIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the Files
            Toast.makeText(this, "Could not create file", Toast.LENGTH_SHORT).show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = Uri.fromFile(photoFile);

            takePicIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            takePicIntent.putExtra(android.provider.MediaStore.EXTRA_SIZE_LIMIT, "720000");
            startActivityForResult(takePicIntent, REQUEST_IMAGE_CAPTURE);
            setResult(RESULT_OK, takePicIntent);
        }
    } else
    {
        //Make a toast if there is no camera app installed.
        Toast toast = Toast.makeText(this,"No program to take pictures",Toast.LENGTH_SHORT);
        toast.show();
    }
}

我添加了 logcat:

FATAL EXCEPTION: main
 Process: lt.vilniausbaldai.vilniausbaldaiofflinedefektai, PID: 14330
 Theme: themes:{}
 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {lt.vilniausbaldai.vilniausbaldaiofflinedefektai/lt.vilniausbaldai.vilniausbaldaiofflinedefektai.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
     at android.app.ActivityThread.deliverResults(ActivityThread.java:3733)
     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776)
     at android.app.ActivityThread.-wrap16(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5461)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
  Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
     at java.util.ArrayList.get(ArrayList.java:308)
     at lt.vilniausbaldai.vilniausbaldaiofflinedefektai.MainActivity.onActivityResult(MainActivity.java:135)
     at android.app.Activity.dispatchActivityResult(Activity.java:6456)
     at android.app.ActivityThread.deliverResults(ActivityThread.java:3729)
     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776) 
     at android.app.ActivityThread.-wrap16(ActivityThread.java) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:148) 
     at android.app.ActivityThread.main(ActivityThread.java:5461) 
     at java.lang.reflect.Method.invoke(Native Method)

createPhotoThumbnail方法:

private void createPhotoThumbnail(ArrayList<Bitmap> thumbnail){
    this.imageGrid = (GridView) findViewById(R.id.gridView);
    this.bitmapList = new ArrayList<>();
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");

    try {
        file.createNewFile();
        FileOutputStream fo = new FileOutputStream(file);
        fo.write(bytes.toByteArray());
        fo.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    try {
        for(int i = 0; i < thumbnail.size(); i++) {
            thumbnail.get(i).compress(Bitmap.CompressFormat.JPEG, 100, bytes);

            this.bitmapList.add(thumbnail.get(i));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.imageGrid.setAdapter(new ImageAdapter(this, this.bitmapList));
    imageGrid.invalidate();
}

创建ImageFile方法:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());
    //String timeStamp = "picTesting";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

    File image = File.createTempFile(
            timeStamp,  /* prefix */
            ".png",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    //Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_LONG).show();
    return image;
}

最佳答案

错误很可能发生在这一行:

if(thumbnail.get(0) != null && thumbnail.size() > 0)

这是因为您首先尝试获取索引 0 处的元素,然后检查是否存在某些元素。

如果您更改这些条件的顺序,它应该可以正常工作:

if(thumbnail.size() > 0 && thumbnail.get(0) != null)

这样,您首先检查是否存在某些元素,并且只有在存在时,您才尝试获取索引 0 处的元素并检查它是否为 null。

关于java - 当我尝试访问应用程序的 Intent 数据时,为什么它会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011152/

相关文章:

java - 如何在imageview上设置捕获的图像

java - 如何在 Firebase 中保存位置信息

android - 在 cordova/on android 应用程序中,使用 https 的请求失败但使用 http 的相同请求成功

android - 从联系人选择器中过滤掉 Facebook 联系人

html - 图片在我的网站上损坏,但一般都能正常工作

java - 时间轴不适用于 'some' 持续时间

java - 电子商务网站的批处理应该保存在同一个应用程序中还是不同的应用程序中?

android - 使用 adb 或 Eclipse 唤醒 Android(就在调试之前)?

php - 如何在 WooCommerce 产品描述中显示所有图片

html - 动态创建的图像布局