'How can I pass a mutable list of type custom object between fragments?

I am trying to pass a mutable list of custom object type SavedRecipes from one fragment to be displayed in a recyclerview on another fragment, however I am struggling to work out how to pass this list.

I have the code below:

RecipePage.kt

class RecipePage : Fragment() {

var allSavedRecipes = mutableListOf<SavedRecipes>()
lateinit var savedRecipe: SavedRecipes
lateinit var id: String

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_recipe_page, container, false)
    val args = this.arguments
    id = args?.get("id").toString()

    view.addToCollection.setOnClickListener {
        saveRecipe()
        val bundle = Bundle()
        bundle.putStringArrayList("allsaved", allSavedRecipes)
        val savedRecipePage = SavedRecipesFragment()
        savedRecipePage.arguments = bundle
        
    }

    return view
}

The line

bundle.putStringArrayList("allsaved", allSavedRecipes)

is where I want to be passing the list of allSavedRecipes to the second fragment. How can I accomplish this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source