I need to catch a SQLiteException in a Composable Button click event. I am executing a Room function to Insert a record. It has a Unique constraint field/index.
I found the following code.
And found Stackoverflow link
I tried the accepted option and the third option, but did not work.
Here is my code:
ADO ///////
interface houseDAO {
@Insert(onConflict = OnConflictStrategy.ABORT )
@Throws(SQLiteException::class)
suspend fun addHouse(houseEntity: HouseEntity)
//More DAO functions
}
Repository ////////
class InventoryRepository (val inventoryDB: InventoryDB){
suspend fun addhouseToRoom(houseEntity: HouseEntity){
inventoryDB.houseDao().addHouse(houseEntity)
}
//More functions
}
Viewmodel //////////
class InventoryViewModel(val repository: InventoryRepository): ViewModel() {
fun addhouse(house: HouseEntity) {
viewModelScope.launch {
repository.addhouseToRoom(house)
}
}
//More functions
}
Composable function ///////////
//More functions
Column(
modifier = Modifier
.padding(top = 22.dp, start = 6.dp, end = 6.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
val coroutineScope = rememberCoroutineScope()
//Commented line because the addfloor function does not returns any value
//val (loadResult, setLoadResult) = remember { mutableStateOf<String?>(null) }
Button(
onClick = {
coroutineScope.launch {
withContext(Dispatchers.IO) {
try {
viewModel.addfloor(
FloorEntity(
0,
houseId!!.toLong(),
infloor,
"$location.$infloor"
)
)
mToast("Floor Added", mContext)
} catch (e: SQLiteException) {
msgbox(
mContext,
e.message.toString(),
"Floor Could not be Added"
)
}
}
}
},
colors = ButtonDefaults.buttonColors(Color.Blue)
) {
Text(text = "Add Floor in to House")
}
}
//More functions
The error is catched in another place on the application where I have a catch all errors segment.
I tried directly in the Viewmodel and it work.
DAO and Repository code is the same
Viewmodel ////////
Composable Function ////////
I removed the Toast message for simplicity and added the success message as part of the try code. I added the Context from the Compose function.