I'm working on an app with a bottom navigation bar and struggle when trying to access a sharedViewModel's data across fragments and adapters. My code is already quite full so I'll be trying to list it up in short here. If needed, I can of course supply the whole code.
Because of different fragments having to access the same data, I created a sharedViewModel class DeactivatedElementsViewModel
(that's where things start to get complicated). In an exemplary fragment there is the fragment class DeactivatedJumpElementsFragment : Fragment(R.layout.deactivated_jump_elements_fragment)
accompanied by the adapter myAdapter : RecyclerView.Adapter<MyAdapter.ViewHolder>()
which equips a list inside the fragment with buttons and strings.
In the fragment class I begin with lateinit var sharedViewModel: DeactivatedElementsViewModel
and lateinit var elementeAusStand: Map<String,Array<Any>>
before successfully working with the sharedViewModel
in e.g. onViewCreated
(inside the fragment) like so elementsFromStand= sharedViewModel.elementsFromStand
.
Now I struggle with accessing data from the sharedViewModel
inside the adapter
's function onBindViewHolder
.
I tried different approaches like the following:
- directly loading
elementsFromStand
insideonBindViewHolder
by implementing thesharedViewModel
there which leads to the error "Can't access ViewModels from detached fragment" - loading
elementsFromStand
insideonBindViewHolder
via the sharedViewModel declared in the fragment's class likeval elementsFromStand= DeactivatedJumpElementsFragment().elementsFromStand
which led to the error of the sharedViewModel being called before initialized. I tried to intercept this byif (DeactivatedJumpElementsFragment()::elementsFromStand.isInitialized){val elementsFromStand = DeactivatedJumpElementsFragment().elementsFromStand}
which simply won't ever be true/ run in runtime although the variableelementsFromStand
is indeed initialized inonViewCreated()
- using nested functions, trying to call the variable elementsFromStand via a function
getSharedViewModelVariable
fromonCreate()
but I fail to successfully retrieve it this way.
That's where I need help. How do I (easily?) access the view model's variables from my adapter? Thanks for reading and for any hint!