Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing getExternalStorageDirectory

Tags:

android

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?

like image 672
jason m Avatar asked Jan 18 '16 22:01

jason m


People also ask

How do I access external files on Android 11?

Users can see which apps have the READ_EXTERNAL_STORAGE permission in system settings. On the Settings > Privacy > Permission manager > Files and media page, each app that has the permission is listed under Allowed for all files. If your app targets Android 11, keep in mind that this access to "all files" is read-only.

What can I use instead of getExternalStoragePublicDirectory?

then you have to use getExternalStorageDirectory() instead of getExternalStoragePublicDirectory() . Example: If you want to create a directory in the internal storage if not exists.

What is getExternalStorageDirectory?

getExternalStorageDirectory() : return the primary external storage root directory. Context. getExternalFilesDir(String type) : return the absolute path of the directory on the primary external storage where the application can place its own files.

What method is used to check whether an external storage media is available?

Android External Storage Example Project StructuregetExternalStorageState() is a static method of Environment to determine if external storage is presently available or not.


2 Answers

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.

like image 145
Gujarat Santana Avatar answered Oct 16 '22 17:10

Gujarat Santana


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:

  • Android Marshmallow permission model on OS 4.0 READ_EXTERNAL_STORAGE permission always not granted

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

like image 25
frogatto Avatar answered Oct 16 '22 18:10

frogatto