0

In my kotlin Android app, I want to create a new file in the external storage folder. I have the following code:

if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
    Log.e("TAG", "${Environment.getExternalStorageState()}")
    return
}

var directory: File? = null
var file: File? = null

directory = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "SecretsApp")
try {
        directory?.mkdirs()
} catch (e: SecurityException) {
        Log.e("TAG", e.toString())
        return
}


if (directory != null) {
    try {
        var filename = "$groupName-privatekey.secretsapp"
        Log.i("AttachmentProcessing", filename)
        file = File(directory, filename)
        var created = file.createNewFile()
    } catch(e: Exception) {
        Log.e("TAG", e.toString()
        return
    }
}

My manifest.xml has <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> too set. However, when I run the above code, I get an Exception at the createNewFile line as java.io.IOException: No such file or directory. Any idea why I am not able to create the file ? I am sure there is no file existing by that name there and even if a file exists, I want it to be over-written. How to fix this ?

Sankar
  • 6,192
  • 12
  • 65
  • 89
  • have you added run time permission? – Pavya Mar 22 '18 at 10:12
  • @Pavya At runtime I do not get any permission dialog itself. Do I need to add something else to my manifest or code to allow android to ask for permissions at runtime ? – Sankar Mar 22 '18 at 10:18
  • http://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/ – Pavya Mar 22 '18 at 10:22

1 Answers1

-1

I have tested your code it is an issue of runtime permission please use runtime permission and it will work. Follow the link below https://developer.android.com/training/permissions/requesting.html

avez raj
  • 2,055
  • 2
  • 22
  • 37