-1
ArrayList<File> files = allFiles(Environment.getExternalStorageDirectory());

private ArrayList<File> allFiles(File root){
    ArrayList<File> arrayList = new ArrayList<>();
    File files[] = root.listFiles();

    for(File file:files){
        if(file.isDirectory()){
            arrayList.addAll(allFiles(file));
        }else{
            arrayList.add(file);
        }
    }
    return arrayList;
}

I am trying to list out all of the files on my android device. the above code, some exception is raised:

2020-01-24 15:20:31.048 23877-23877/com.example.readingfromstorage E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.readingfromstorage, PID: 23877 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.readingfromstorage/com.example.readingfromstorage.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array

please help me to solve this problem. thanks;

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
shibu
  • 1
  • 1

1 Answers1

0

You are getting null file array because you dont have read permission to access internal stroage

Make sure you that you have read persmission to access

 int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permissionCheck== PackageManager.PERMISSION_GRANTED){
            //this means permission is granted and you can do read and write
        }else{
            requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
        }

also dont forget to mention permission in Manifest also.

Bunny
  • 1,044
  • 12
  • 23