How to list all files from sdcard directory in android

If we are developing an application like a PDF scanner or any application which requires image processing ,it is important to store and retrieve the files in android sdcard.  Suppose if all the files used in our project is stored in particular folder, like whatsapp image folder, we might be needed to display all files as well in some screen. In this tutorial we will learn how to list all files inside a directory.

Contents

  • How to implement the function for retrieving the list of files.
  • How to display the file if the file is an image
  • What are the permissions required for listing the files from sdcard

How to implement the function for retrieving the list of files

For listing all files inside a directory just add the below function and call it in the place you required. The function will return a string arraylist with the list of file names.

private ArrayList<String> FetchImages() {

ArrayList<String> filenames = new ArrayList<String>();
    path = Environment.getExternalStorageDirectory()
            + File.separator + "Your folder name";

    File directory = new File(path);
    File[] files = directory.listFiles();

    for (int i = 0; i < files.length; i++)
    {

     String file_name = files[i].getName();
     // you can store name to arraylist and use it later
      filenames.add(file_name);
    }
return filenames;
}

How to display the file if the file is an image

If your folder consist of image files only and you want to display all images in a recyclerview you can add the files names to arraylist and set to recyclerview adapter and use the below code to set image to ImageView in adapter class

String path = Environment.getExternalStorageDirectory()
+ File.separator + "your folder";
Bitmap bitmap = BitmapFactory.decodeFile(path+"/"+itemsList.get(i).getName());
holder.your_image_view.setImageBitmap(bitmap);

If you are not familiar with implementing recyclerview  please refer the following tutorial

Android RecyclerView example

What are the permissions required for listing the files from sdcard

For listing the files from sdcard you need to provide read external storage permission for the application. For getting permission if the target api is less than 21 you just need to add the following line to your AndroidManifest.xml file . But if the target api is greater or equal to 21 you need to get the permission from the user dynamically.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

If you don’t know how to get the permission dynamically in android ,please do refer the following tutorial.

Request permission dynamically example in android

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *