Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法以编程方式将文件夹或文件写入android设备_Android - Fatal编程技术网

无法以编程方式将文件夹或文件写入android设备

无法以编程方式将文件夹或文件写入android设备,android,Android,我无法读取或写入我的Android设备。在同一个主题上也有类似的问题(我已经实现了代码),但它们似乎都会使我的应用程序崩溃 Button btnUpload = (Button) findViewById(R.id.btnUpload); File created = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "MyNewFolde

我无法读取或写入我的Android设备。在同一个主题上也有类似的问题(我已经实现了代码),但它们似乎都会使我的应用程序崩溃

Button btnUpload = (Button) findViewById(R.id.btnUpload);
File created = new File(Environment.getExternalStorageDirectory().getPath()
                        + File.separator + "MyNewFolder" + File.separator + "created");    

if (created.isDirectory()) {    
    File[] contents = created.listFiles();

    //Should not trigger as directory check is in place
    if (contents == null) {            //<--not adding this section causes a crash
        btnUpload.setEnabled(false);
    } 

    //Check to see if the number of files is 0
    else if (contents.length == 0) {
        btnUpload.setEnabled(false);
    } 

    //All checks pass. Enable button
    else {
        btnUpload.setEnabled(true);
    }
}
Button btnUpload=(Button)findviewbyd(R.id.btnUpload);
创建的文件=新文件(Environment.getExternalStorageDirectory().getPath())
+File.separator+“MyNewFolder”+File.separator+“created”);
if(created.isDirectory()){
File[]contents=created.listFiles();
//不应触发,因为目录检查已到位

如果(contents==null){/非常感谢Mike和Commonware

概要:除了清单文件中的权限外,我们还需要在运行时检查权限(如果没有权限,则请求权限)。问题在于API级别23

根据一些阅读添加了两行代码。这不是最好的或遵循所有最佳编码实践,而是一个快速而肮脏的解决方案,因此请进行相应修改

if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }

我已将此添加到主要活动的开头,以便在剩余时间内获得权限及其设置。

请查看。使用LogCat检查与崩溃相关的Java堆栈跟踪:如果您无法理解该堆栈跟踪,请编辑您的问题以提供该问题,以及清单和创建代码Mike指出,如果您的
targetSdkVersion
为23或更高,请确保在运行时将您的代码显示在请求
WRITE\u EXTERNAL\u STORAGE
的位置。请求权限时应尽可能接近实际使用情况。