Martin
Martin

Reputation: 227

Cannot access removable SD card from my android app (Android Studio)

I am developing an app where I have to search PDF files in my Internal Storage as well as removable SD card. This is code that I am using:

private void Search_Dir(File dir) {

        try {
            String pdfPattern = displayName;  //(displayName = pdf_name.pdf)
            File FileList[] = dir.listFiles();

            if(FileList != null)
            {
                for(int i = 0 ; i < FileList.length ; i++)
                {

                    if(FileList[i].isDirectory())
                    {
                        Search_Dir(FileList[i]);
                    }
                    else
                    {
                        if(FileList[i].getName().endsWith(pdfPattern))
                        {
                            path = FileList[i].toString();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Here path is a String which will contain the path of the PDF that I want to search. And the name of PDF that I am searching is displayName

I am calling this method like this:

Search_Dir(Environment.getExternalStorageDirectory());

But unfortunately this method searches the PDF in my internal storage only. I have defined READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE and I am requesting these permissions run time also.

I don't know if this matters but it was working perfectly fine before. I was getting the path for PDF files located in SD card also. But I did factory data reset on my phone and then again I installed my app. Since then its not working.

It is working on files located in my internal storage like /storage/emulated/0/..... but not on removable SD card.

My Question: What is it that I am doing wrong. Or is there any other method which I should use to search the files which will work on both internal storage and removable SD card.

Thank you.

Upvotes: 0

Views: 497

Answers (1)

Handsome Hunk
Handsome Hunk

Reputation: 157

Environment.getExternalStorageDirectory() gives you the path to primary storage of the device, which you can also call as internal storage.

You will have to get the root path of the removable storage (if available) in order to search for files there. If you don't want much headache then you can simply make a storage chooser or implement any one from a bunch of already available and tested ones.

Upvotes: 1

Related Questions