rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

kotlinでのIntentの受け取り(Intent.dataはNullable) Android開発

2020 May 03.
2020 May 02.

val GET_FILE_CODE: Int = 1100
fun onClick(view: View?) {
    if ( buttonGetFile == view ) {
        val getFileIntent = Intent(Intent.ACTION_GET_CONTENT)
        getFileIntent.setType("*/*")
        startActivityForResult(getFileIntent, GET_FILE_CODE)
    }
}

override fun onActivityResult(requestCode: Int , resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data )
    try {
        if (requestCode == GET_FILE_CODE && resultCode == RESULT_OK) {
            val filePath: String = data!!.getDataString().replace("file://", "")
                // getDataString() does not accept nullable arguement
            val decodedfilePath: String = URLDecoder.decode(filePath, "utf-8")
            strFileName = decodedfilePath
        }
    } catch (e: UnsupportedEncodingException) {
        // TO DO ON EXCEPTION
    }
}