From 4e414be7fbbedbf51ca20cc21036cd2007fe3e30 Mon Sep 17 00:00:00 2001 From: Florian Date: Tue, 14 Jan 2025 11:24:14 +0100 Subject: [PATCH] AddViewModel --- .../at/xaxa/ledger/ui/add/AddViewModel.kt | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/Ledger/app/src/main/java/at/xaxa/ledger/ui/add/AddViewModel.kt b/Ledger/app/src/main/java/at/xaxa/ledger/ui/add/AddViewModel.kt index bea04de..850ec50 100644 --- a/Ledger/app/src/main/java/at/xaxa/ledger/ui/add/AddViewModel.kt +++ b/Ledger/app/src/main/java/at/xaxa/ledger/ui/add/AddViewModel.kt @@ -1,2 +1,54 @@ package at.xaxa.ledger.ui.add +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import at.xaxa.ledger.data.Entry +import at.xaxa.ledger.data.EntryRepository +import at.xaxa.ledger.data.db.Entry.EntryEntity +import at.xaxa.ledger.ui.home.EntryListUIState +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + + +// UI State to hold a list of games +data class EntryListUi( + val entries: Flow> = flow{emit(emptyList()) } +) + +class AddViewModel( + private val savedStateHandle: SavedStateHandle, + private val repository: EntryRepository +) : ViewModel() { + + var addUiState by mutableStateOf(EntryListUi()) + private set + + + fun addEntryToDB(entry: Entry){ + viewModelScope.launch { + try { + val entryEntity = Entry( + id = entry.id, + name = entry.name, + date = entry.date, + amount = entry.amount, + categoryID = entry.categoryID + ) + + withContext(Dispatchers.IO) { + repository.insertEntry(entryEntity) // Add game to the database + } + // Optionally, log or update UI state to reflect that the game was added + } catch (e: Exception) { + } + } + } +} \ No newline at end of file