androidkotlinandroid-intenturi

How to Save URI returned from ACTION_CREATE_DOCUMENT and Use In Different Activity/Fragment


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)

Solution

    1. Create variable of ActivityLauncher.

    2. Initialize the launcher in Oncreate()

    3. Then call above method with launch(what you have written above that code).

    4. 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 = ""
         }
    }