Search code examples
androidimageuri

Image not found /Documents/Image:XXXX


I'm selecting an image from the gallery selector after pressing a button, and then filling a RecyclerView with these images. However, it seems the pictures I'm selecting cannot be found...

To open the gallery selector I do:

ActivityResultLauncher<String> GetImageFromGallery = registerForActivityResult(new ActivityResultContracts.GetContent(),
        new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(@Nullable Uri uri) {
                if (uri != null) {
                    ArrayList<String> temp = new ArrayList<>(0);
                    temp.add(uri.getPath());
                    img_data.add(temp);
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

// Button
Button btn_add = root.findViewById(R.id.btn_add_image);
btn_add.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        GetImageFromGallery.launch("image/*");
    }
});

where img_data is an `ArrayList<ArrayList> and mAdapter is the adapter of a RecyclerView. Inside the RecyclerView I'm reading the images to show in an ImageViewer as follows:

        try {
        viewHolder.getphoto().setImageBitmap(BitmapFactory.decodeStream(viewHolder.getphoto().getContext().getApplicationContext().getContentResolver().openInputStream(Uri.parse(localDataSet.get(position).get(0)))));

//Or viewHolder.getphoto().setImageBitmap(BitmapFactory.decodeFile(localDataSet.get(position).get(0)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

However, none of above works. I'm getting stuck with a not found file error. Path are always of style /Documents/Image:XXXX where X are numbers. What am I doing wrong?


Solution

  • Following the code in my question, use this to add the uri as a String:

    temp.add(uri.toString());
    

    and this to load the image:

    viewHolder.getphoto().setImageURI(Uri.parse(localDataSet.get(position).get(0)));
    

    Although if possible use Glide to load the image. Without Glide was extremely slow, but with it it wasn't. To add glide add the following dependencies intro build.gradle module:

    implementation 'com.github.bumptech.glide:glide:4.12.0'
    // Glide v4 uses this new annotation processor -- see https://bumptech.github.io/glide/doc/generatedapi.html
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
    

    and then to load the picture:

        Glide.with(viewHolder.getphoto().getContext())
                .load(Uri.parse(localDataSet.get(position).get(0)))
                .into(viewHolder.getphoto());