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

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Objects.requireNonNull only showing null location.Is it Right?
It is not require, please check this answer
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()

1 Comment

@Diego If you found this helpful pls remember to upvote or mark it as answered stackoverflow.com/help/someone-answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.