Issue
I have created entity class with auto generated id.
@Entity(tableName = "todo_list")
data class Todo(
@PrimaryKey(autoGenerate = true)
var itemId: Long = 0L,
@ColumnInfo(name = "todo_title")
val title: String,
@ColumnInfo(name = "todo_description")
val description: String)
And viewmodel class
class TodoViewModel(application: Application) : AndroidViewModel(application) {
val readAllData: LiveData<List<Todo>>
private val repository: TodoRepository
init {
val todoDao = TodoDatabase.getInstance(application).todoDao()
repository = TodoRepository(todoDao)
readAllData = repository.readAllData
}
fun addTodo(todo: Todo) {
viewModelScope.launch(Dispatchers.IO) {
repository.addTodo(todo)
}
}
fun deleteTodo(todo: Todo) {
viewModelScope.launch (Dispatchers.IO ){
repository.deleteTodo(todo = todo)
}
}
}
But when I wanna add todo entry on button click it still requires to add long.
mTodoViewModel.addTodo(Todo(titleText, descriptionText))
Am I adding new object wrong or there is any way to fix it?
Solution
The problem is data class constructor requires 3 parameters but only 2 are being passed.
now even though, you have provided a default value to the data class but since it comes first in the data class, it needs to be defined even if the value is the same,i.e., 0L.
I have four suggestions, you can use whichever suits you best.
- Pass
0L
as the key.
should look something like this-
mTodoViewModel.addTodo(Todo(0L, titleText, descriptionText))
or
fun addTodo(titleText:String, descriptionText:String) {
viewModelScope.launch(Dispatchers.IO) {
repository.addTodo(Todo(0L, titleText,descriptionText))
}
}
- Slightly change the database structure.
@Entity(tableName = "todo_list")
data class Todo(
@ColumnInfo(name = "todo_title")
val title: String,
@ColumnInfo(name = "todo_description")
val description: String,
@PrimaryKey(autoGenerate = true)
var itemId: Long = 0L
)
Here since the default value is in the last there is no need to send 0L
- Use a secondary constructor with your data class.
should look something like this -
@Entity(tableName = "todo_list")
data class Todo(
@PrimaryKey(autoGenerate = true)
var itemId: Long = 0L,
@ColumnInfo(name = "todo_title")
val title: String,
@ColumnInfo(name = "todo_description")
val description: String
) {
constructor(title: String, description: String) : this(title, description, 0L)
}
Here now you have 2 constructors one with 3 parameters, the other with 2.
- assign values directly to each constructor something like this.
Todo(title = titleText, description = descriptionText)
Here automatically OL
will be considered
I believe all of these should work perfectly fine. If you have any further doubts feel free to leave a comment.
Answered By - lets start coding
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.