Android Studio中File对象的FileList()方法返回NULL的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Rec_Mervyn/article/details/77995862

今天想写一个能获取文件列表的demo,期间遇到了一个问题:File对象的FileList()方法返回NULL。


我的代码

private void initFiles() {
    rootPath = Environment.getExternalStorageDirectory().getPath();
    Log.d(TAG, "initFiles: "+rootPath);
    scanFiles(rootPath);
}

private void scanFiles(String path) {
    fileList.clear();
    File dir = new File(path);
    Log.d(TAG, "scanFiles: "+dir.toString());
    File[] subFiles = dir.listFiles();
    if (subFiles != null) {
        Log.d(TAG, "scanFiles: subFiles.length " + subFiles.length);
        for (File file : subFiles)
            fileList.add(file);
    }
    else
        Log.d(TAG, "scanFiles: subFiles is empty ");
    fileAdapter.notifyDataSetChanged();
    curFilePathTextView.setText(path);
}

api文档中描述

If this abstract pathname does not denote a directory, then this method returns null(如果这个路径名不是一个目录,那么这个方法返回null)

百思不得其解,路径是没错的,那问题到底出在哪了?


1. 一开始我没有为WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE动态申请运行时权限,认为是权限出了问题,就加上了。

if (ContextCompat.checkSelfPermission(MainActivity.this, "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(MainActivity.this, "android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[] {"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE"}, 1);
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);
                break;
            default:
                break;
        }
    }

仍然没解决问题。


2. 然后看到console中有一个warm
Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
就把build.gradle中的minSdkVersion调到19即4.4
还是没有解决.


3. 最后查到一篇文章http://blog.csdn.net/xiaopang_love_study/article/details/70339303,看到了他查到解决方案:临时将build.gradle中的targetSdkVersion改为23以下,运行,竟然解决了问题,并且再把该值该回去仍然可行。


问题解决了,但不知道问题到底出在了哪。

猜你喜欢

转载自blog.csdn.net/Rec_Mervyn/article/details/77995862