'How can I save data from intent to text file to documents folder?

I am receiving an object that I want to save with timestamp to text file in the phone's documents folder. I have currently added the permissions lines to AndroidManifest.xml

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

Getting it to save .txt to downloads folder. But there is nothing in the file and the size is 0mb.

    private fun saveFile() {

        val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "text/plain"
            putExtra(Intent.EXTRA_TITLE, "device.txt")
            // Optionally, specify a URI for the directory that should be opened in
            // the system file picker before your app creates the document.
            //putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
        }
        startActivityForResult(intent, createFile)
    }
private var measureLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        Log.d(result.resultCode.toString(), "code ${result.resultCode}")

        if (result.resultCode == Activity.RESULT_OK) {
            // There are no request codes
            tvPalaute?.text = getString(R.string.status_ok)

            val data: Intent? = result.data

            if (data != null) {
                val measureData = data.getStringExtra("M")

                if (measureData != null) {
                    val date = Date()
                    Timestamp(date.time)
                    Log.d(date.toString(), "date")

                    tvPalaute?.text = getString(R.string.status_ok) + "\n \n" + measureData

    }

I have tried following things to save the measureData to text file.

But none of those worked and crashed the application with error something related to file read only.

Caused by: android.system.ErrnoException: open failed: EROFS (Read-only file system)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source