I have an app that connects to an api using retrofit and displays the data in a recyclerview, I have now added another fragment that displays this data on a google map fragment.
The map fragment is fine when I navigate to it after the recyclerview fragment, however if I start the app and navigate straight to the map fragment then none of the data is there and the size of the data is 0.
Here is the snippet from the map fragment:
val livePointViewModel: ChargePointViewModel by activityViewModels()
livePointViewModel.getChargePointQuery()
// bind viewmodel to view
binding.livePointsViewModel = livePointViewModel
binding.lifecycleOwner = this
livePointViewModel.status.observe(viewLifecycleOwner, Observer {
when (it) {
ChargeQueryAPIStatus.LOADING -> Timber.d("0 - map points query loading")
ChargeQueryAPIStatus.DONE -> {
Timber.d("0 - map points query complete")
livePointViewModel.listOfChargePoints.observe(viewLifecycleOwner, Observer {
it?.let {
Timber.d("1 - map points observed")
when{
it.isEmpty() -> Timber.d("2.1- map points live charge point size:${it.size}")
it.isNotEmpty() -> generateMap()
}
}
})
}
}
})
Here is my .getChargePointQuery function:
fun getChargePointQuery() {
viewModelScope.launch {
_status.value = ChargeQueryAPIStatus.LOADING
try {
_response.value = "Loading"
val chargeQuery: ChargeQuery?
// check if using live location or using static postcode
if (useLocation.value == true) {
chargeQuery = ChargeApi.retrofitService.getChargeQueryObjectLocation(
myLatitude.value.toString(),
myLongitude.value.toString(),
distance.value.toString(),
limit.value.toString()
)
} else { // using postcode
chargeQuery = ChargeApi.retrofitService.getChargeQueryObjectPostcode(
postcode.value.toString(),
distance.value.toString(),
limit.value.toString()
)
}
_listOfChargePoints.value = convertChargePoints(chargeQuery.chargeDevices)
_status.value = ChargeQueryAPIStatus.DONE
}
} catch (e: Exception) {
_status.value = ChargeQueryAPIStatus.ERROR
_response.value = "Failure: ${e.message}"
}
}
}
My recyclerview fragment submits the list of data to the adapter and then only makes the view visible when the status changes to DONE - however in the map fragment, I tried to do the same but when in the DONE branch my list of data still seems to be empty and the map will not be generated.
Here is my whole project if that helps: https://github.com/Kovah101/ChargeMyCar
I was able to resolve this myself. Comparing my live list to my live map fragments there were nearly identical except for how you would navigate to them. For the live list I would set the variable
useLocation.value = true, however for the live map fragment the variable wasnt initialised. I now set the default value ofuseLocation.value = truebefore any navigation takes place.