J Lukas
J Lukas

Reputation: 61

Handling depreciated onActivityResult when calling from Adapter

This might be a dumb question but I just started programming and already ran into this depreciation issue. I have an activity with a Recycler View adapter and used several request codes to send data with Intents from the adapter to the activity.

For example:

In recycler view:

val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"}
    activity.startActivityForResult(intent, saveRequestCode)

and in the activity:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==saveRequestCode&&resultCode == RESULT_OK) {

            if (data != null) {
                uri = data?.data!!
                saveData(uri)
            }
        }
}

I can handle the depreciation when calling from the activity

by declaring:

val saveIntent=registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {

            if (result.data != null) {

                uri = result.data?.data!!

                saveData(uri)
            }
        }
    }

and calling the intent:

  Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"
      saveIntent.launch(this)

    }
   

but how to handle it from the adapter?

Upvotes: 2

Views: 941

Answers (1)

J Lukas
J Lukas

Reputation: 61

Since registerForActivityResult requires implementation AppCompatActivity I could not call it from the adapter but I could pass the saveIntent variable as a parameter for the recyclerView adapter. So, actually it turned out to be as simple as declaring the ActivityResultLauncher variable in the activity

saveIntent=registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
    
                if (result.data != null) {
    
                    uri = result.data?.data!!
    
                    saveData(uri)
                }
            }
        }

and passing to the adapter

  adapter=ItemAdapter(list,saveIntent)

and in the adapter

class ItemAdapter(private var list: MutableList<Item>,
                   private val saveIntent: ActivityResultLauncher<Intent>,
                 ) :
    RecyclerView.Adapter<ItemAdapter.ItemListViewHolder>() {

   override fun onBindViewHolder(holder: ItemListViewHolder, position: Int) {

        holder.save.setOnClickListener{
  Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "*/*"
          
          saveIntent.launch(this)
        }

Upvotes: 4

Related Questions