I'm writing an app for Android 10 using kotlin.
The app has to read file named number.txt from internal storage.
But it always fails to do so:
java.io.FileNotFoundException: /storage/emulated/0/number.txt: open failed: EACCES (Permission denied)
Here what I have in my manifest:
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
I have to only read the file, so there is no write permission in manifest.
Here is my code, as you can see I use runtime permissions:
This is the function that requests permission and if it granted, reads the file:
private fun setupPermissions() {
val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
if (permission == PackageManager.PERMISSION_GRANTED) {
val path = "/storage/emulated/0"
val file = File("$path/number.txt")
val pln = file.readText()
plnText.text = pln
}
else{
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 101)
}
}
Then I call setupPermissions in my onCreate method.
That's it, I don't understand why isn't it working.
Thanks.
EDIT
I don't know what is the reason, but I just changed my code to this:
if (permission == PackageManager.PERMISSION_GRANTED) {
val file = File("/storage/emulated/0/number.txt")
val pln = file.readText()
Log.i("IKO_APP", pln)
// plnText.text = path.toString()
}
And it works without any error! I'm wondering though why?