7. June 2019

How to solve Android Emulator java.io.FileNotFoundException open failed: EACCES (Permission denied)

Following error in Android application is very annoying and you may waste several hours by hunting the root cause:

D/file: java.io.FileNotFoundException: /storage/emulated/0/Download/20190604_084533.jpg: 
open failed: EACCES (Permission denied)

It might occur even when the manifest is correct and contains proper permission:

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

Here is sample code which will pass on file existence check, but the execution will fail on readBytes:

var file:File = File("/storage/emulated/0/Download/20190604_084533.jpg")
if (file.exists()) {
    val content:ByteArray;
    Log.d("file", "exist")
    try {
        content = f.readBytes()
     } catch (FileNotFoundException) {
        Log.d("file", e.toString())
     }

} else {
     Log.d("file", "does not exist")
}

To fix this problem it is necessary to go to Settings – Apps – My App – Permission.

Access to Storage is probably disabled. Tap Storage to enable it:

With enabled Storage option, the application was able to read the file.

To solve this problem in a proper way, it’s necessary to add a request for permission to the code. Here is a sample in Kotlin:

val MY_READ_EXTERNAL_REQUEST : Int = 1
if (checkSelfPermission(
    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), MY_READ_EXTERNAL_REQUEST)
}

You can find more details about requesting permissions in Android documentation.

23. April 2019

Android Studio Unresolved reference: activity_main – R.layout and R.id

You can easily run into mysterious errors with Android Studio. Here is one.

Suddenly all references related to R.layout or R.id stopped to work and build failed with a message like this:

Compilation error. See log for more details
Unresolved reference: activity_main
Unresolved reference: url_edittext
Unresolved reference: update_button

The code looked like this:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

I tried clean, builds, rebuilds. Nothing helped. The problem was caused by simple import which accidentally occurred in Activity file:

import android.R

After removing this line the whole project was working again and even code hinting was correct.