0

Below code gives a warning when I run Inspect code. How can I change it to fix the warning?

File contents = new File(context.getExternalFilesDir(null).getAbsolutePath(), "Contents");
            if (!contents.exists()) {
                contents.mkdirs();
            }

Warning:

Method invocatiom 'getAbsolutePath' may produce 'NullPointerException'

and File mkdirs() is ignored

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Diego
  • 937
  • 8
  • 24

2 Answers2

1

You can use boolean to get the result of mkdirs()

boolean isMkDirsSuccess = contents.mkdirs();
Log.e("TAG","This is the value of isMkDirsSuccess " + isMkDirsSuccess );

for NullPointerException you can use

File contents = new File(Objects.requireNonNull(context.getExternalFilesDir(null)).getAbsolutePath(), "Contents");
//requireNonNull needs min API = 19

Hope this will help!

Rahul Gaur
  • 1,661
  • 1
  • 13
  • 29
0

From the docs:

Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using Environment#getExternalStorageState(File).

You need to do some checking first:

File externalDir = context.getExternalFilesDir(null);
if(externalDir == null) {
    throw new IllegalStateException("No External files directory found.");
}

if(Environment.getExternalStorageState(externalDir).equals(Environment.MEDIA_MOUNTED)) {
    throw new IllegalStateException("External Storage not mounted correctly.");
}

File contents = new File(externalDir.getAbsolutePath(), "Contents");
if (!contents.exists()) {
   contents.mkdirs();
}

You can replace the exceptions with flags, or logs or whatever your programme needs.

https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

https://developer.android.com/reference/android/os/Environment#getExternalStorageState()

Blundell
  • 75,855
  • 30
  • 208
  • 233
  • @Diego If you found this helpful pls remember to upvote or mark it as answered https://stackoverflow.com/help/someone-answers – Blundell Feb 15 '20 at 23:10