无法从任何 Android 文件夹中获取文件

Not able to get files from any Android folder

我是 android 的新人,正在尝试测试一些东西。我有这个简单的应用程序,我只想从任何 android 文件夹中读取文件。到现在为止,我只是检查了我从以下内容中了解到的路径

context.getExternalFilesDir(null);

&

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)

得到的路径是这样的

/storage/emulated/0/ then rest of the folders

我已完成所有操作,在清单文件和应用程序中请求许可。我检查即使授予了权限并且文件夹路径也正确但是 File.listFiles() 给我空指针异常。

请看下面的代码:

清单文件中的权限

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

获取权限并尝试检查文件的代码

 if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},101);
        Toast.makeText(getApplicationContext(),
                "No permission yet",
                Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(getApplicationContext(),
                "Permission already granted",
                Toast.LENGTH_SHORT).show();
       
        File dcimPath = new File("/storage/emulated/0/bluetooth"); //This path is correct
        
        File[] files = dcimPath.listFiles(); // gives null pointer exception
        Log.i("files length ",files.length+"");
    }

     @Override
     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 101){
        if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Toast.makeText(getApplicationContext(),
                    "Permission granted",
                    Toast.LENGTH_SHORT).show();
            File dcimPath = new File("/storage/emulated/0/bluetooth/"); 

            File[] files = dcimPath.listFiles(); //gives error
            Log.i("files length ",files.length+"");
        }
        else{
            Toast.makeText(getApplicationContext(),
                    "Permission denied",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

错误

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

尝试将此行添加到 Android Manifest 文件

        android:requestLegacyExternalStorage="true"

这用于读取 Shared Storage 除了应用程序的私有存储空间。如果您想了解更多,请阅读 this...

希望这对您有所帮助。随时要求澄清...