I'm trying to add sports API data to a list of categories to be synchronized with a scrollable tabrow, but the list is always empty and just shows the titles and icons, not the API data. The application is working perfect with a dummy list, and this is not the case when adding from an API.
I attached some code samples to make it obvious. I hope I make a clear explanation, and someone may give an answer.
ListViewModel
class ListViewModel: ViewModel() {
val tournamentItemList: MutableList<Category>
get() = items
private val items = mutableStateListOf<Category>()
fun addTournamentItem(item: Category){
items.add(item)
}
}
GetData
@Composable
fun GetData(
team: TeamStatsResponse, rankList: List<StandingsItemItem?>
) {
val data: ArrayList<Int> = ArrayList(3)
val viewModel: TournamentStateViewModel = viewModel()
viewModel.addTournamentItem(
Category(
"Standings",
Icons.Default.TableRows,
onClick = {},
data.forEach {
TopTeamsPoints(
rankList[it]!!.rank!!,
rankList[it]!!.team!!.logo!!,
rankList[it]!!.team!!.name!!,
rankList[it]!!.all!!.played!!,
rankList[it]!!.all!!.win!!,
rankList[it]!!.all!!.draw!!,
rankList[it]!!.all!!.lose!!,
rankList[it]!!.points!!
)
}
)
)
viewModel.addTournamentItem(
Category(
"Clean Sheets",
Icons.Default.CleaningServices,
onClick = {},
data.forEach {
TopTeamsClean(
1, team.team!!.logo!!,
team.team.name!!, team.fixtures!!.played!!.total!!,
team.cleanSheet!!.total!!
)
}
)
)
etc...
}
FetchData
fun FetchData(
mainViewModel: MainViewModel = hiltViewModel()
) {
when(
val stateA = mainViewModel.pLStandings.collectAsState().value
) {
is PLStandingsState.Empty -> {
Text(text = "No data available")
}
is PLStandingsState.Loading -> {
Text(text = "Loading...")
}
is PLStandingsState.Error -> {
Text(text = stateA.message)
}
is PLStandingsState.Success -> {
when(val stateB = mainViewModel.leagueStatsState.collectAsState().value) {
is LeagueStatsState.Empty -> {
Text(text = "No data available")
}
is LeagueStatsState.Loading -> {
Text(text = "Loading...")
}
is LeagueStatsState.Error -> {
Text(text = stateB.message)
}
is LeagueStatsState.Success -> {
GetData(team = stateB.teamData, rankList = stateA.data)
}
}
}
}
}
@Preview
@Composable
fun TabSyncCompose() {
val context = LocalContext.current
val viewModel: TournamentStateViewModel = viewModel()
val list = viewModel.tournamentItemList
if (list.isNotEmpty()) {
TabSyncComposeScreen(list)
} else {
//This toast always appears
Toast.makeText(context, "Empty", Toast.LENGTH_SHORT).show()
}
}
OK, In the attached code samples above, without any edits, the data was successfully fetched from the API and added successfully to the list. The real problem is with the 'data' array list of 3 integers. While the wanted items from the API are only 3, then the loop is not required. For me, everything is now working perfectly after removing 'add' and 'foreach{}' blocks.