How do I save the URI returned from Intent.ACTION_CREATE_DOCUMENT
and then use this URI to be used in a different Activity or Fragment? Since startActivityForResult is deprecated, I'm incredibly lost.
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "application/pdf"
}
startActivityForResult(intent)
Create variable of ActivityLauncher.
Initialize the launcher in Oncreate()
Then call above method with launch(what you have written above that code).
Also I created a Constants.kt file with a companion object to save uri.
private lateinit var createTxtLauncher: ActivityResultLauncher
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
createTxtLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){result ->
if(result.resultCode == Activity.RESULT_OK){
val uri: Uri? = result.data?.data
Constants.uri = uri.toString()
}
}
binding.saveButtonId.setOnClickListener {
createAndSaveFile()
}
}
private fun createAndSaveFile(){
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
setType("text/plain")
putExtra(Intent.EXTRA_TITLE, "chinmay.txt")
}
createTxtLauncher.launch(intent)
}
Constants.kt file
class Constants {
companion object {
var uri: String = ""
}
}