I have an app, which contains some fragments. Each of them, are responsible for displaying other piece of data, that they obtain from the api call by using the base currency from the database. Recently, I've added a toolbar, so user can change the base currency at any moment.
I've started to working on it, and I've implemented the nav_graphs and stuff like that. The communication between two fragments (just for now) are just good. I can go from one of the fragments that calls the api, to that where user can change the base currency, and after clicking on textview, I can go back to fragment before.
The app crashes, whenever I want to update base currency in database. It's because whenever user click on icon, and went to the fragment where he can select new base currency, the spinner is waiting for a selection, whenever user click on any of the names, the app crashes with this error
java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()
Im not sure, but I think it is because the fragment that user were before calling the changing base currency fragment, was observing stuff that came from api. To do that call, program have to provide base currency. Whenever user change it, it will be different, so that may cause the crash, I don't know.
I thought about something like "stopping observing" the api call, or just abort it, and whenever user will back to this fragment, the api will be called once again. Is this possible to do?
To get data from api call, my program execute following funs (in order):
private fun getBaseCurrency() {
mDatabaseViewModel.baseCurrency.observe(requireActivity(), Observer {
mBaseCurrency = it.toString()
if (mBaseCurrency != "default") {
fetchFromViewModel()
}
})
}
private fun fetchFromViewModel() {
mViewModel =
ViewModelProvider(
this,
CurrencyViewModelFactory(CurrencyRetrofitRepository(mRetrofitService))
)
.get(CurrencyRetrofitViewModel::class.java)
mViewModel.fetchLatestRates(mBaseCurrency)
mViewModel.latestCurrencyRates.observe(viewLifecycleOwner, Observer {
...
}
calling the latestCurrencyRates causing the app crash.