【问题标题】:I can't create files or directories in android studio with kotlin我无法使用 kotlin 在 android studio 中创建文件或目录
【发布时间】:2019-05-30 16:24:44
【问题描述】:

我需要在我的 Android 应用程序中创建一个文本文件,但它不允许我这样做。验证它是否已创建的方法返回我是假的。我怎么能这样做?

我已经为应用程序 manifest.xml 分配了写入权限,但它也不适用于我。 我也提出了权限请求。

我在 manifest.xml 上分配的权限是这样的:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

写文件的代码,我是这样写的:

    fun writeFile() {
        if (ContextCompat.checkSelfPermission(this@GenerateCodeActivity,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    PackageManager.PERMISSION_GRANTED)
        }

        val sd_main = File(Environment.getExternalStorageDirectory().absolutePath+"/FilesMyApp")
        var success = true
        if (!sd_main.exists()) {
            success = sd_main.mkdir()
        }
        if (success) {
            val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")
            val hola = "HOLA QUE TAL"
            if (!sd.exists()) {
                success = sd.mkdir()
            }
            if (success) {
                // directory exists or already created
                val dest = File(sd, "${this@GenerateCodeActivity.auth.currentUser?.uid}.txt")
                try {
                    // response is the data written to file
                    FileOutputStream(dest).use { it.write(hola.toByteArray()) }
                } catch (e: Exception) {
                    // handle the exception
                }

            } else {
                // directory creation is not successful
            }
        }
    }

我想输入指定的文本字符串,但它不允许我进入“if (success)”区域。

【问题讨论】:

  • requestPermissions() 不是阻塞调用。到返回时您还没有权限。
  • 我该怎么做?是否有必要将我所指出的内容放入 manifest.xml 中?事实是,我是 android 编程新手。
  • 是的,清单中需要WRITE_EXTERNAL_STORAGE。您需要将 I/O 工作转移到一个单独的函数中,从两个地方调用它。一种是checkSelfPermission() 表示您已经获得许可。另一个来自您的onRequestPermissionsResult() 回调,如果您确定您已获得权限。见developer.android.com/training/permissions/requesting
  • 我已经完成了你告诉我的所有事情,但我仍然做不到。我已将其包含在清单中,我已经提出了写作请求,并且我已经创建了onRequestPermissionsResult() 的方法它仍然对我不起作用。

标签: android file kotlin


【解决方案1】:
val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")

您尚未指定目录。使用:

val sd = File(sd_main, "${this@GenerateCodeActivity.auth.currentUser?.uid}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2021-01-16
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多