Java.lang.IndexOutOfBoundsException:无效的索引0,大小为0,Android

时间:2018-07-09 16:04:40

标签: java android android-gradle build.gradle

我可能在DAYS一周内就收到此错误,但仍然无法解决,也没有人可以帮助我。

我正在使用Instagram克隆应用程序来创建类似Instagram的应用程序。我遇到了这些错误,我无法修复,这里的人似乎也无法修复。

07-09 11:48:43.307 19532-19532/tabian.com.hash E/AndroidRuntime: FATAL EXCEPTION: main
Process: tabian.com.hash, PID: 19532
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at tabian.com.hash.Share.GalleryFragment.setupGridView(GalleryFragment.java:159)
at tabian.com.hash.Share.GalleryFragment.access$300(GalleryFragment.java:38)
at tabian.com.hash.Share.GalleryFragment$3.onItemSelected(GalleryFragment.java:134)

该文件没有错误,甚至没有警告或错别字。我只有在尝试通过手机访问相机时才得到此信息。我试图更改代码,移动代码并添加代码,但没有任何效果。我尝试减少targetSdkVersionminSdkVersion,但仍然出现错误。

public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";

//constants
private static final int NUM_GRID_COLUMNS = 3;

//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;

//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_gallery, container, false);
    galleryImage = view.findViewById(R.id.galleryImageView);
    gridView = view.findViewById(R.id.gridView);
    directorySpinner = view.findViewById(R.id.spinnerDirectory);
    mProgressBar = view.findViewById(R.id.progressBar);
    mProgressBar.setVisibility(View.GONE);
    directories = new ArrayList<>();
    Log.d(TAG, "onCreateView: started.");

    ImageView shareClose = view.findViewById(R.id.ivCloseShare);
    shareClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: closing the gallery fragment.");
            Objects.requireNonNull(getActivity()).finish();
        }
    });

    TextView nextScreen = view.findViewById(R.id.tvNext);
    nextScreen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: navigating to the final share screen.");

            if(isRootTask()){
                Intent intent = new Intent(getActivity(), NextActivity.class);
                intent.putExtra(getString(R.string.selected_image), mSelectedImage);
                startActivity(intent);
            }else{
                Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
                intent.putExtra(getString(R.string.selected_image), mSelectedImage);
                intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
                startActivity(intent);
                Objects.requireNonNull(getActivity()).finish();
            }

        }
    });

    init();

    return view;
}

private boolean isRootTask(){
    return ((ShareActivity) Objects.requireNonNull(getActivity())).getTask() == 0;
}

private void init(){
    FilePaths filePaths = new FilePaths();

    //check for other folders inside "/storage/emulated/0/pictures"
    if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
        directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
    }
    directories.add(filePaths.CAMERA);

    ArrayList<String> directoryNames = new ArrayList<>();
    for (int i = 0; i < directories.size(); i++) {
        Log.d(TAG, "init: directory: " + directories.get(i));
        int index = directories.get(i).lastIndexOf("/");
        String string = directories.get(i).substring(index);
        directoryNames.add(string);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
            android.R.layout.simple_spinner_item, directoryNames);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    directorySpinner.setAdapter(adapter);

    directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "onItemClick: selected: " + directories.get(position));

            //setup our image grid for the directory chosen
            setupGridView(directories.get(position));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

private void setupGridView(String selectedDirectory){
    Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
    final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);

    //set the grid column width
    int gridWidth = getResources().getDisplayMetrics().widthPixels;
    int imageWidth = gridWidth/NUM_GRID_COLUMNS;
    gridView.setColumnWidth(imageWidth);

    //use the grid adapter to adapter the images to gridview
    GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
    gridView.setAdapter(adapter);

    //set the first image to be displayed when the activity fragment view is inflated
    try{
        setImage(imgURLs.get(0), galleryImage, mAppend);
        mSelectedImage = imgURLs.get(0);
    }catch (ArrayIndexOutOfBoundsException e){
        Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
    }

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));

            setImage(imgURLs.get(position), galleryImage, mAppend);
            mSelectedImage = imgURLs.get(position);
        }
    });

}

private void setImage(String imgURL, ImageView image, String append){
    Log.d(TAG, "setImage: setting image");

    ImageLoader imageLoader = ImageLoader.getInstance();

    imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            mProgressBar.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            mProgressBar.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            mProgressBar.setVisibility(View.INVISIBLE);
        }
    });
}
}

有人可以帮我吗?这对我来说很重要。

EDITTT !!

   private void setupGridView(String selectedDirectory){
    Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
    final ArrayList<String> imgURLs = 
FileSearch.getFilePaths(selectedDirectory);

    //set the grid column width
    int gridWidth = getResources().getDisplayMetrics().widthPixels;
    int imageWidth = gridWidth/NUM_GRID_COLUMNS;
    gridView.setColumnWidth(imageWidth);

    //use the grid adapter to adapter the images to gridview
    GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
    gridView.setAdapter(adapter);

    if (imgURLs.isEmpty()) {
        // Array list is empty, handle accordingly
    } else {
        //set the first image to be displayed when the activity fragment view is inflated
        try {
            setImage(imgURLs.get(0), galleryImage, mAppend);
            mSelectedImage = imgURLs.get(0);
        } catch (ArrayIndexOutOfBoundsException e) {
            Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " + e.getMessage());
        }

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));

                setImage(imgURLs.get(position), galleryImage, mAppend);
                mSelectedImage = imgURLs.get(position);
            }
        });
    }
}

The errors I see

1 个答案:

答案 0 :(得分:2)

此行:

Data

返回空的final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory); ,即未返回文件路径。因为您没有检查ArrayList,所以您试图imgURLs.isEmpty()索引get()的索引0,该索引不存在。因此,将抛出IndexOutOfBoundsException

您可以通过在继续之前检查imgURLs是否包含至少一项来避免此崩溃。例如:

imgURLs