I'm trying to learn jetpack compose and tried to make an easy app where you can add restaurants together with a score in an overview list using room.
However, everytime I try to type a word in the textfield, the textfield is not updated and remains empty. I would expect that updating the locationName in the onValueChange function would trigger an update of the state as it is part of a LiveData class. How can I solve this without having to make a seperate UI model in my modelView and having it converted to my entity object in case the data needs to be persisted?
My compose function
@Composable
fun AddItemScreenBody(modifier: Modifier = Modifier.Companion) {
VerticalScroller {
Column(modifier) {
var locations = addItemViewNodel.location.observeAsState()
FilledTextField(
value = locations.value!!.locationName,
onValueChange = { data -> locations.value!!.locationName = data },
label = { Text(stringResource(R.string.name), style = TextStyle(color = Color(0xFFC7C7C7))) })
}
}
}
My viewmodel
class AddItemViewModel () : ViewModel() {
var location : LiveData<LocationEntity> = MutableLiveData(LocationEntity())
}
My data model
@Entity(tableName = "locations")
class LocationEntity @Ignore constructor () {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
@ColumnInfo(name = "location_name")
var locationName: String = ""
constructor (id: Long, locationName: String, category: Category) : this()
{
this.id = id
this.locationName = locationName
}
}
locations.value!!.locationName = data
updating thevalue
won't help instead you should calladdItemViewNodel.location.setValue(new Instance of LocationEntity with desired locationName)
– Habib Kazemi