Choose a pdf from storage and open it with a pdf app

Viewed 104

I like to choose a pdf file from storage. Afterwards it should open the choosen pdf file with a pdf reader app, that the user chooses. I can choose a file, but afterwards the app crashes and it throws:

android.content.ActivityNotFoundException: No Activity found to handle Intent

I tried:

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

    btnTravels.setOnClickListener {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        //val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "application/pdf"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        startActivityForResult(intent, R.integer.request_code_pdf)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == R.integer.request_code_pdf) {
            if (data != null) {

                Log.i("gotresult", data.data.toString())

                data.data?.also {uri ->
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.setDataAndType(uri,"document/pdf")
                    intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
                    startActivity(intent)
                }
            }
        }
    }
}

The Log.i shows me this. It doesn't really look like a Filename:

content://com.android.providers.downloads.documents/document/msf%3A462052
1 Answers

Replace:

                val intent = Intent(Intent.ACTION_VIEW)
                intent.setDataAndType(uri,"document/pdf")
                intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
                startActivity(intent)

with:

                val intent = Intent(Intent.ACTION_VIEW, uri)
                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                startActivity(intent)

document/pdf is not a valid MIME type, and you need to grant permission to the viewer app to read the content.

Also, remove intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true), since you are not handling multiple documents.

It doesn't really look like a Filename

It is not supposed to be a filename. It is supposed to be a Uri pointing to a document that the user selected via ACTION_OPEN_DOCUMENT.

Related