访问 android 10 中的文件时出现问题:- android studio

problem having accessing files in android 10 :- android studio

Android 10 不允许我从外部存储访问我的文件。在 android 9 中,我的应用程序正常工作 fine.I 将我的 phone 从 android 9 更新为 android 10,我的应用程序停止响应。

main_activity.java

File directory;
    File path;
    File[] listfile;
    //File listFiles;
    ArrayList<String> arrayList;

directory = Environment.getExternalStorageDirectory();

        path = new File(directory.getAbsolutePath()+ "/myfile/");

        arrayList = new ArrayList<String>();
        mycardview.setAdapter(new ImageAdapter(listimage.this, arrayList));

if (path.isDirectory()) {
            listfile =path.listFiles();
            for (int i = 0; i < listfile.length; i++) {
                arrayList.add(listfile[i].getAbsolutePath());
            }
            Collections.shuffle(arrayList);

错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rajiv/com.example.rajiv.listimage}: java.lang.NullPointerException: Attempt to get length of null array at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3374) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7682) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) Caused by: java.lang.NullPointerException: Attempt to get length of null array at com.example.rajiv.listimage.onCreate(listimage.java:74) at android.app.Activity.performCreate(Activity.java:7815) at android.app.Activity.performCreate(Activity.java:7804) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)

我已经在网上查过了问题不在代码中 google 已在 android 10 中应用安全补丁,因此代码无法正常工作我还使用了清单权限和运行时权限..

另一个被 Google 变化捕获。

https://developer.android.com/training/data-storage

您需要使用 MediaStore 或存储访问框架 (SAF),详细信息 https://developer.android.com/training/data-storage/shared 用于您的应用私有目录之外的文件。

虽然快速解决方法是暂时选择退出 https://developer.android.com/training/data-storage/compatibility 但这只会在 Android 11

之前有效