Вывод любого файла в текстовом виде (выбор файла из файлового менеджера) Kotlin

Всем добрый день, Есть кнопка для открытия системного файлового менеджера, где пользователь выбирает 1 файла(txt,pdf,jpeg). После выбора файла ты должен его открыть и прочитать в текстовое поле (т.е. Прочитать все содержимое файла в виде строки)

Проблема заключается в том, что у меня не получается выбрать любой файл из файлового менеджера и прочитать его в текстовом виде(у меня открывается по кнопке файловый менеджер, но не дает выбрать ни один файл)Как это исправить?

Ниже представлен код моего приложения

?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <!-- A TextView to show the data from the text file-->

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="156dp"
        android:layout_marginBottom="68dp"
        android:text="PICK FILE" />

   

    <TextView
        android:id="@+id/textView"
        android:layout_width="308dp"
        android:layout_height="146dp"
        android:layout_centerInParent="true"
        android:gravity="center" />

</RelativeLayout>


package com.example.writeandread
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.io.*
import java.nio.charset.Charset

class MainActivity : AppCompatActivity() {

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

        // Declaring and initializing the TextView from the layout
        val myTextView = findViewById<TextView>(R.id.textView)
        val myInputStream: InputStream
        val button1 = findViewById<Button>(R.id.button1)


        button1.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "application/pdf"
            intent.type = "application/txt"
            intent.type = "application/jpeg"
            fun getFileContent(FileName: String): String {
                val f = File(FileName)
                return f.readText(Charset.forName("UTF-8"))
            }
            startActivityForResult(intent, PICK_FILE)
        }


    }
    companion object {
        const val PICK_FILE = 99
    }
}

Ответы (1 шт):

Автор решения: Vind Iskald

Это не добавляет типы, а перезаписывает:

intent.type = "application/pdf"
intent.type = "application/txt"
intent.type = "application/jpeg"

Так все работает:

class MainActivity : AppCompatActivity() {

    companion object {
        const val PICK_FILE = 99
        const val TEXT = "text/*"
        const val IMAGE = "image/*"
        const val PDF = "application/pdf"
    }

    var myTextView: TextView? = null

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

        // Declaring and initializing the TextView from the layout
        myTextView = findViewById(R.id.content)
        val button1 = findViewById<Button>(R.id.button)
        button1.setOnClickListener {
            onButtonClick(TEXT, IMAGE, PDF)
        }
    }

    private fun onButtonClick(vararg types: String) {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*"
        intent.putExtra(Intent.EXTRA_MIME_TYPES, types)
        startActivityForResult(intent, PICK_FILE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_FILE && resultCode == RESULT_OK) {
            data?.data?.let { uri ->
                val sb = StringBuilder()
                contentResolver
                    .openInputStream(uri)
                    ?.bufferedReader(Charset.forName("UTF-8"))
                    ?.forEachLine {
                        sb.append(it)
                    }
                val content = sb.toString()
                myTextView?.text = content
            }
        }
    }
}

Надо только не забыть в манифест добавить

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

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

    <application
    ...>
      ...
    </application>
</manifest>

→ Ссылка