I want to retrieve a specific column from my Android ROOM Database but it kept returning an empty list.
Here is the code on my DAO interface:
@Query("SELECT * FROM expense_table ORDER BY category ASC")
fun getAllExpenses(): Flow<List<Expense>>
@Query("SELECT DISTINCT category FROM expense_table ORDER BY category ASC")
fun getAllCategories(): Flow<List<String>>
getAllExpenses works perfectly, but for some reason getAllCategories kept returning empty lists. I even made getAllExpenses ordered by category to make sure the column does exist and it does. Reducing the query to a simple "SELECT category FROM expense_table" doesn't work by the way.
I tried looking up on how to solve this but I can't find any solutions. Which is to be expected as this is such a simple query that I'm sure I'm just doing something incredibly stupid and overlooking it.
Here are my other codes, I largely just copied the getAllExpenses code so I think the DAO is the problem since it's the only one that's different but I'm not sure.
Repository:
fun getAllExpenses() = expenseDao.getAllExpenses()
fun getAllCategories() = expenseDao.getAllCategories()
ViewModel:
var expenseRepository: ExpenseRepository
private val _expenseList = MutableStateFlow<List<Expense>>(emptyList())
val expenseList: StateFlow<List<Expense>> get() = _expenseList
private val _categoryList = MutableStateFlow<List<String>>(emptyList())
val categoryList: StateFlow<List<String>> get() = _categoryList
init {
expenseRepository = ExpenseRepository(expenseDatabase.expenseDao())
viewModelScope.launch {
expenseRepository.getAllExpenses().collect { expenses ->
_expenseList.value = expenses
}
expenseRepository.getAllCategories().collect { categories ->
_categoryList.value = categories
}
}
}
Activity (this is just a placeholder screen for testing)
composable(route = AppScreen.TEST_SCREEN.name) {
val list by viewModel.expenseList.collectAsState()
val catList by viewModel.categoryList.collectAsState()
TestScreen(list, catList)
}
The screen would display the list size and list contents for each list. The expense list is displayed correctly but the category list would always show a size of 0.