9

Using some pretty simple android code I am trying to access a folder according to the following logic:

public void try_to_navigate_local_dir(){
    Environment e = new Environment();
    ArrayList<String> filesList = new ArrayList<String>();
    String sd_card = Environment.getExternalStorageDirectory().toString() + "/subdir_x";
    File file = new File( sd_card ) ;
    File list[] = file.listFiles();
    for( int i=0; i< list.length; i++) {
        filesList.add( list[i].getName() );
    }
}

Where subdir_x is created by another application on my phone.

I can view in those folders using file manager, yet my code returns null when I try to file.listFiles().

How may I access these files?

frogatto
  • 28,539
  • 11
  • 83
  • 129
jason m
  • 6,519
  • 20
  • 69
  • 122

2 Answers2

3

Prior to Marshmallow, follow @Cory Charlton's answer. However his answer for Android Marshmallow (6.0) won't work.

Actually as of Android 6.0 (API level 23), we don't have the following permission anymore.

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

For more information, please this question:

By the way, Environment e = new Environment(); is useless, remove it.

Community
  • 1
  • 1
frogatto
  • 28,539
  • 11
  • 83
  • 129
0

Make sure your AndroidManifest.xml has the appropriate permission:

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

The next problem might be your filename. I use the following in one of my applications and it works (note the trailing slash and lack of leading slash):

directory = new File(Environment.getExternalStorageDirectory(), "Subdirectory/")
final File[] files = directory.listFiles();

The next problem might be the path Environment.getExternalStorageDirectory() is giving you. Newer devices have a partition on the internal storage that emulates an sd card and Environment.getExternalStorageDirectory() can return this rather than the real sd card.

Cory Charlton
  • 8,868
  • 4
  • 48
  • 68