I'm getting an exception when I try to write content to a file created with an Intent. The error is an IOException error "No content provider:Intent {...}". I see the file created in "My Drive", but it has no contents.
I want to output the text to a text file. This is a step on the way toward outputting data to an audio wav file. That's my goal.
I'm basically doing this tutorial, except I'm using Kotlin:
https://www.youtube.com/watch?v=CGD1Kr7A77Y&ab_channel=Sam'sAndroidClassroom
Can anyone help me with this? I've provided the code below, which is in an Activity file. "buttonFiles" is the button I'm adding a Click Listerner to.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_extra)
buttonFiles.setOnClickListener{
val intent = Intent()
.addCategory(Intent.CATEGORY_OPENABLE)
.setType("text/plain")
.putExtra(Intent.EXTRA_TITLE, "testFileSam.txt")
.setAction(Intent.ACTION_CREATE_DOCUMENT)
startActivityForResult(Intent.createChooser(intent, "text file"), 1)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == RESULT_OK) {
var uri = data
try{
if(uri != null) {
var outputStream = contentResolver.openOutputStream(Uri.parse(uri.toString()))
val charset = Charsets.UTF_8
outputStream?.write("Hello, is anybody out there!!!".toByteArray(charset))
}
}catch( e: IOException){
Log.d("Debug"," IOException = " e.message)
}
}
}
CodePudding user response:
var uri = data
data
is an Intent?
. You are assigning it to a variable named uri
, confusing both of us.
Change that to:
val uri = data?.data
Now, uri
will be a Uri?
. You can use that with your null
check. And, from there, you can use contentResolver.openOutputStream(uri.toString())
to open the OutputStream
.
This is also why you were running into a problem originally. You created a string representation of an Intent
, then tried parsing that as as Uri
, which is not going to work.