registerForActivityResult is not working consistently

441 Views Asked by At

I implemented a registerForActivityResult in fragment to launch another activity and to get data from the activity. The problem is that the registerForActivityResult sometimes works and sometimes it doesn't. I put a log to be printed and I found that when it works the log is not printed. That means it doesn't go into the function.

val getContent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result:ActivityResult ->

        Log.i("register", "out")

        if(result.resultCode == Activity.RESULT_OK)
        {
            val data = result.data
            val note = data?.getParcelableExtra<Note>("note")

            Log.i("register", "in")
            adapter.mNotes[notePos].title = note?.title.toString()
            adapter.mNotes[notePos].notes = note?.notes.toString()

            adapter.notifyItemChanged(notePos)
        }
    }

private fun initRecycleView()
    {
        adapter  = NotesAdapter(notesList){note, pos ->
            val intent = Intent(this.context, NotingActivity::class.java).apply {
                putExtra("note",note)
                notePos = pos
            }
            getContent.launch(intent)
        }


        rvItems.adapter = adapter
        rvItems.layoutManager = GridLayoutManager(this.context, 2)

        (rvItems.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

    }

  override fun onBackPressed() {

        intent.putExtra("note", note)
        setResult(Activity.RESULT_OK, intent)
        finish()
        super.onBackPressed()

    }
0

There are 0 best solutions below