Android 10 is not letting me access my files from external storage. In android 9 my app was working fine.I updated my phone from android 9 to android 10 and my app stopped responding.
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);
ERROR :
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)
I have checked on internet the problem is not in code google have applied a security patch in android 10 so the code isnt working i have also used permission on manifest as well as runtime permission ..
Another one caught out by Google changes.
See https://developer.android.com/training/data-storage
You need to use MediaStore or Storage Access Framework (SAF), details https://developer.android.com/training/data-storage/shared for files outside of your App's private directories.
Though as a quick fix is to temporarily opt out https://developer.android.com/training/data-storage/compatibility but this will only work until Android 11