Search code examples
javaandroidandroid-fileandroid-storage

Access files from a location in Android


I am trying to access(only read) the list of files available in a location in android device using below code but I am getting null as a response. Please correct me if I am missing something. I tried the below code in Android 11 and I am expecting it should work from Android 9 onwards.

File[] files = new File("/storage/emulated/0/Android/data/MyApp/files/").listFiles();

I am getting null for the above code. Also I add the below permissions in my AndroidManifest.xml file.

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

Also having the permission granting request in code as well and added the below attribute in the application tag in AndroidManifest.

android:requestLegacyExternalStorage="true"

After adding all the above still I am facing the issue to get the files from the given location. Am I doing it in a right way? My objective is to access the files after the application is launched and these files will be added manually into the location by user using ADB commands.


Solution

  • please try this way

    for internal files (/data/data)

    File[] files = getApplicationContext().getFilesDir().listFiles();
    

    for external files (/sdcard)

    File[] files =  getApplicationContext().getExternalFilesDirs("your path");