【问题标题】:Fix warning NullPointerException in android修复 android 中的警告 NullPointerException
【发布时间】:2020-05-12 16:08:52
【问题描述】:

当我运行检查代码时,下面的代码会发出警告。如何更改它以修复警告?

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

警告:

方法调用“getAbsolutePath”可能会产生“NullPointerException”

并且文件 mkdirs() 被忽略

【问题讨论】:

    标签: android


    【解决方案1】:

    你可以使用boolean得到mkdirs()的结果

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

    对于NullPointerException,你可以使用

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

    希望这会有所帮助!

    【讨论】:

    • Objects.requireNonNull 只显示空位置。对吗?
    • 不需要,请查看this answer
    【解决方案2】:

    来自文档:

    共享存储可能并不总是可用,因为用户可以弹出可移动媒体。可以使用 Environment#getExternalStorageState(File) 检查媒体状态。

    你需要先做一些检查:

    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();
    }
    

    您可以将异常替换为标志、日志或您的程序需要的任何内容。

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

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

    【讨论】:

    猜你喜欢
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2015-09-10
    相关资源
    最近更新 更多