kotlinsupportfragmentmanager

Going back to a Fragment from an Activity / RecyclerView.ViewHolder and Passing data


I have an app that I open an activity from a fragment, select an item from the RecyclerView and then populate that original fragment with the data from the item they select. It works the first time, but the data doesn't seem to get carried over back to the fragment and then if I try it a second time it says "No view found for id 0x7f0a001a (com.tipsy.cardgenie:id/ScrollView01) for fragment AddCardFragment{dc1763f}". I think I'm either not going back correctly to the fragment that created the activity or using supportfragmentmanager in the wrong way.

class QAViewHolder(view: View) : RecyclerView.ViewHolder(view) {

itemView.setOnClickListener { v: View ->
 val addCard = AddCardFragment()
                    val args = Bundle()
                    val activity = v.context as AppCompatActivity
                    args.putString("sport", cards.sport).toString()

                    activity.supportFragmentManager.beginTransaction()
                        .replace(R.id.content, addCard)
                        .addToBackStack(null)
                        .commit()
}
}

In the Fragment onCreate I have, which is not seeing the data I set in the activity:

 val bundle = this.arguments
            if (bundle != null) {
                sport = bundle.getString("sport").toString()
            }

The content view is in the layout of the fragment I am going back too.

<FrameLayout
        android:id="@+id/content"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
</FrameLayout>

Thank you in advance for any help or suggestions!!


Solution

  • I can suggest that if it is not necessary to open new activity then you can have a list or recyclerview in fragment so you can get updated data inside the fragment and perform whatever you want. But if you want to get back data from particular activity to fragment you can open that activity from fragment using startActivityForResult(yourIntent,requestCode) this method, and after selecting an item from recyclerview using interface you can get back data into activity and send back using this snippet to fragment

    val myIntent = Intent()
        myIntent.putExtra("data","your data")
        setResult(RESULT_OK,myIntent)
        finish()
    

    Now you can declare the below method in your fragment and get your data in that

     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // you can get your whatever data in @data object
    }
    

    and then update your code as your need...and no need to replace a fragment from another activity.