'Crash when on click button
The folllowing is the error:java.lang.ClassCastException: com.example.myhouse.MainActivity cannot be cast to com.example.myhouse.TasklistFragment$Callbacks at com.example.myhouse.TasklistFragment.onAttach(TasklistFragment.kt:50)
Where the code for tasklist at line 50 is
interface Callbacks{
fun addTaskToViewModel(task: Task, destinationTasklistType: Int)
fun deleteTaskFromViewModel(tasklistType: Int, adapterPosition: Int)
fun getTaskListFromViewModel(tasklistType: Int) : LinkedList<Task>
}
override fun onAttach(context: Context) {
super.onAttach(context)
callbacks = context as Callbacks?
}
Solution 1:[1]
Always use safe casting to avoid class cast exception which is causing the crash in this case. Like this
override fun onAttach(context: Context) {
super.onAttach(context)
callbacks = context as? Callbacks?
}
Other than this, the context you are passing is not of type Callbacks which is causing the casting to fail. Maybe provide some more info to solve this issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Syed Faizan Ali |
