Android: how to get image files from a directory in view.setBackgroundDrawable ()

I am trying to create an application that can receive images from a directory on an android phone and display them in a layout. It seems that I am working towards the solution in the reverse order. I know to use view.setBackgroundDrawable(Drawable.createFromPath(String pathName));to display the image, but I do not know how to get the path to the image from the directory.

I have a vague idea of ​​what to do, but I would like clarification on this issue. I think the next step is to use:

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    File file[] = Environment.getExternalStorageDirectory().listFiles();
}

But how can I filter files so that only image files are saved in mine file[]? Such as .png or .jpg / .jpeg files? And after that, should I use files[].getPathor files[].getAbsolutePath? I would save the result in String[].

Basically, I ask you to confirm that the above code should work. And also, how can I filter to store only image files such as .png, .jpgand .jpeg.

Thank you for your time.

+3
source share
3 answers

You want to do something like this for filtering:

File[] file = folder.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String filename) {

                    return filename.contains(".png");
                }
            });

If you want the path to the file with the let file to be able to specify the file in file[0], you would do the following:

file[0].getAbsolutePath();

+7
source

You want to implement FileFilter and pass it listFiles . You can create one that filters out only image files as you specified.

EDIT: and you want to use getAbsolutePath()as an argument createFromPath.

+1
source

, .Png,.jpg

private File[] listValidFiles(File file) {
    return file.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String filename) {
            File file2 = new File(dir, filename);
            return (filename.contains(".png") || filename.contains(".jpg") || file2
                    .isDirectory())
                    && !file2.isHidden()
                    && !filename.startsWith(".");

        }
    });
}
0
source

All Articles