Android中意外的ArrayIndexOutOfBoundsException

Android中意外的ArrayIndexOutOfBoundsException,android,indexoutofboundsexception,Android,Indexoutofboundsexception,我的应用程序抛出了一个意外的ArrayIndexOutOfBoundsException,甚至没有告诉我抛出错误的行号。我尝试使用日志来放置消息以检查代码在何处被破坏,我发现数组大小为5,但错误为java.lang.ArrayIndexOutOfBoundsException:length=4;指数=4 我正在使用intent打开相机: File file = createImageFile(); Intent cameraIntent = new Intent(android.

我的应用程序抛出了一个意外的ArrayIndexOutOfBoundsException,甚至没有告诉我抛出错误的行号。我尝试使用日志来放置消息以检查代码在何处被破坏,我发现数组大小为5,但错误为java.lang.ArrayIndexOutOfBoundsException:length=4;指数=4

我正在使用intent打开相机:

File file = createImageFile();
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        Uri uri;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            uri = FileProvider.getUriForFile(pdf_viewer.this, BuildConfig.APPLICATION_ID + ".provider", file);
        else
            uri = Uri.fromFile(file);

        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        startActivityForResult(cameraIntent, REQUEST_CODE);
我的onActivityResult代码是:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (resultCode == Activity.RESULT_OK)
        {
            try {
                new addImageInBack().execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
这是一种异步方法,在该方法中,我的代码每次都会中断:

Log.e("1 - imgRotComp", " OK ");

            ArrayList<String> img_paths = send_pdf_images;

            File f = new File(Environment.getExternalStorageDirectory(),"/CamScan/.tempFiles");
            if(!f.exists())
            {
                f.mkdirs();
            }

            Log.e("a", "OK" + img_paths.size());

            for(int i = 0 ; i < img_paths.size() ; i++)
            {

                Log.e("b", "OK "+img_paths.size());

                int orientation = 0;
                try
                {
                    Log.e("c", "OK");
                    ExifInterface oldExif = new ExifInterface(send_pdf_images.get(i));
                    orientation = oldExif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

                Log.e("d", "OK");
                File a_file = new File(img_paths.get(i));
                Bitmap a_bitmap = BitmapFactory.decodeFile(a_file.getAbsolutePath());

                float a_op_width = a_bitmap.getWidth();
                float a_op_height = a_bitmap.getHeight();

                if (a_op_width < 1500 && orientation == 0)
                    continue;

                Log.e("e", "OK");

                if(orientation == 6 || orientation == 3 || orientation == 8)
                {
                    Matrix rotateMatrix = new Matrix();

                    if (orientation == 6)
                        rotateMatrix.postRotate(90);
                    else if (orientation == 3)
                        rotateMatrix.postRotate(180);
                    else if (orientation == 8)
                        rotateMatrix.postRotate(270);

                    Bitmap rotatedBitmap = Bitmap.createBitmap(a_bitmap, 0, 0, a_bitmap.getWidth(), a_bitmap.getHeight(), rotateMatrix, false);
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

                    try
                    {
                        Calendar c = Calendar.getInstance();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("d-M-yy-H-m-s", Locale.getDefault());
                        String dateTime = dateFormat.format(c.getTime());
                        dateTime = dateTime.replace("-", "");

                        File temp_file = new File(f.toString() + "/", dateTime + ".jpg");

                        temp_file.createNewFile();
                        FileOutputStream fo = new FileOutputStream(temp_file);
                        fo.write(bytes.toByteArray());
                        fo.close();

                        Uri uri = Uri.fromFile(temp_file);
                        String realPath = getRealPathFromURI(uri);

                        Log.e("l1","OK");

                        send_pdf_images.remove(i);
                        send_pdf_images.add(i, realPath);

                        Log.e("l2","OK");

                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }

                }
          }
编辑: PDFViewAdapter.java

package com.example.camscan;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.ArrayList;

public class PDFViewAdapter extends ArrayAdapter<String> {

    Context context;
    ViewHolder viewHolder;
    ArrayList<String> pdf_images = new ArrayList<>();


    public PDFViewAdapter(Context context, ArrayList<String> pdf_images) {
        super(context, R.layout.pdf_image_view, pdf_images);
        this.pdf_images = pdf_images;
        this.context = context;
    }

    @Override
    public int getCount() {
        return pdf_images.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return pdf_images.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {

            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.pdf_image_view, parent, false);
            viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.pdfiv);
            viewHolder.tv = (TextView)convertView.findViewById(R.id.pdftv);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.tv.setTag(position);

        Glide.with(context).load(pdf_images.get(position))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(viewHolder.iv_image);

        viewHolder.tv.setText(""+(position + 1));
        return convertView;

    }

    private static class ViewHolder {
        ImageView iv_image;
        TextView tv;
    }

}

package com.example.camscan;
导入android.content.Context;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ArrayAdapter;
导入android.widget.ImageView;
导入android.widget.TextView;
导入com.bumptech.glide.glide;
导入com.bumptech.glide.load.engine.DiskCacheStrategy;
导入java.util.ArrayList;
公共类PDFViewAdapter扩展了ArrayAdapter{
语境;
持票人持票人;
ArrayList pdf_images=新建ArrayList();
公共PDFViewAdapter(上下文,数组列表pdf_图像){
super(context,R.layout.pdf_image_view,pdf_image);
this.pdf_images=pdf_images;
this.context=上下文;
}
@凌驾
public int getCount(){
返回pdf_图像。大小();
}
@凌驾
public int getItemViewType(int位置){
返回位置;
}
@凌驾
public int getViewTypeCount(){
返回pdf_图像。大小();
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
公共视图getView(最终整数位置、视图转换视图、视图组父视图){
if(convertView==null){
viewHolder=新的viewHolder();
convertView=LayoutInflater.from(getContext()).flate(R.layout.pdf\u image\u视图,父视图,false);
viewHolder.iv_image=(ImageView)convertView.findViewById(R.id.pdfiv);
viewHolder.tv=(TextView)convertView.findViewById(R.id.pdftv);
convertView.setTag(viewHolder);
}否则{
viewHolder=(viewHolder)convertView.getTag();
}
viewHolder.tv.setTag(位置);
Glide.with(context.load)(pdf_images.get(position))
.diskCacheStrategy(diskCacheStrategy.NONE)
.skipMemoryCache(真)
.into(viewHolder.iv_图像);
viewHolder.tv.setText(“+(位置+1));
返回视图;
}
私有静态类视图持有者{
ImageView iv_图像;
文本视图电视;
}
}
这可能是什么原因?
谢谢

我想问题出在这一行:

 File a_file = new File(img_paths.get(i));
尝试记录i的值并尝试i-1。
错误表示需要数组的第四个元素,但数组长度仅为4:0,1,2,3。

我找到了解决方案!我犯了一个非常愚蠢的错误。假设我的网格视图中有4个图像,当我从相机单击新图像时,当我在onActivityResult中收到单击的图像时,我应该用新图像更新网格视图,即,我应该再次调用:

adapter = new PDFViewAdapter(pdf_viewer.this, pdf_viewer.send_pdf_images);
gridView.setAdapter(adapter);
然后我应该调用我在问题中发布的AsyncMethod(抛出错误的地方)。但是我调用AsyncMethod时没有更新适配器,并且再次访问AsyncMethod中的网格视图元素。这就是为什么它一次又一次地显示出相同的数组索引边界外性感觉


非常感谢@Akash Raghav和@julianpjp为您提供的时间和支持。

您可以尝试调试模式,手动单步执行代码,至少知道在哪行之后崩溃,以缩小范围。@Akash Raghav由于网格视图问题而崩溃。请参阅我的编辑。这是我在再次运行后发现的,并且再次发布了网格视图适配器/相关代码。我现在已经发布了。在我从gallery中选择图像的Activity onCreate中,当它第一次被调用时,它似乎工作得很好。但是,当我单击new image from camera向grid view动态添加新图像时,我正在从Activity onResult调用相同的函数,在那里,Crassesi得到了解决方案@AkashRaghav。看看我的答案。谢谢你的时间:-)它不起作用了。如果我输入I-1,它肯定会超出范围,因为我的起始I值是0。更新后它将变为-1。问题似乎是在网格视图中,我正在放大捕获的图像。我设置网格视图的高度和宽度时,一次只能看到其中的4个项目。所以当我点击第五张图片,当它试图充气时,它崩溃了。但若我在点击第四张图片后手动滚动到底部,那个么效果会非常好。我怎样才能纠正这个问题。
adapter = new PDFViewAdapter(pdf_viewer.this, pdf_viewer.send_pdf_images);
gridView.setAdapter(adapter);