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
  • 27,475
  • 10
  • 76
  • 119
jason m
  • 6,081
  • 19
  • 65
  • 117

3 Answers3

10

I have tried this logic in Marshmallow (6.0) :

  1. make sure you have this in your manifest :

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

  1. when try to access external storage please check the permission before entering the logic to read directory :

    public void checkPermissionReadStorage(Activity activity){
             if (ContextCompat.checkSelfPermission(activity,      Manifest.permission.READ_EXTERNAL_STORAGE) !=     PackageManager.PERMISSION_GRANTED) {
    
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
    
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
    
            } else {
    
                // No explanation needed, we can request the permission.
    
                ActivityCompat.requestPermissions(activity,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_STORAGE);
    
                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }
    
  2. and then override this method in your activity :

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PermissionManager.MY_PERMISSIONS_REQUEST_READ_STORAGE: {
                //premission to read storage
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
    
                } else {
    
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(SnapSellAddActivity.this, "We Need permission Storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }
    
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
    
  3. after that you can finally read the external storage in android devices, I tried like this method to read directory in external storage :

    public File getPreviewTempExternalDirectory(Context context) {
        File previewDir = new File(context.getExternalFilesDir(null), PLACE YOUT DIR HERE);
        if (!previewDir.exists()) previewDir.mkdir();
        return previewDir;
    }
    

    and now you have the directory, you can list file or create file there. hope it helps.

Adam Varhegyi
  • 12,015
  • 32
  • 115
  • 205
Gujarat Santana
  • 8,851
  • 16
  • 49
  • 73
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
  • 27,475
  • 10
  • 76
  • 119
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,721
  • 4
  • 47
  • 66