2

I am trying to access my android files through my apk and (initially) list them on my terminal. This is the code I use:

File basePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)getAbsolutePath();
File directory = new File(basePath);
System.out.println("" + directory.toString());
File[] directoryContents = directory.listFiles();

I do succeed printing this path: /storage/emulated/0/Download which actually exists in my android and has some files in it.

When listing files inside that directory using:

for (File file : directoryContents)
    {
        if (file.isFile())
            System.out.println("" + file.getName());
        else
            continue;
    }

I get java.lang.NullPointerException: Attempt to get length of null array

I also included <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> in android's manifest.

My smartphone runs on Android 7.0 if that's of any help.

kamyar haqqani
  • 748
  • 6
  • 19
Darren Col
  • 119
  • 2
  • 9
  • [Lower target SDK version](https://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it), it works. targetSdkVersion 22 – AiChiFan Aug 19 '19 at 09:16

2 Answers2

0

listFiles returns an array if the File instance from which this method is called from is a directory. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) always(i guess) returns a directory( unless you altered the os defaults). so the only thing going wrong is probably lack of permissions;

here is how to ask permissions properly

kamyar haqqani
  • 748
  • 6
  • 19
0

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS replace this line instance of Environment.getExternalStorageDirectory()getAbsolutePath() issue will resolved.