-1

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?
    }
  • so passed `context` isn't an instance of (probably interface) `Callbacks`. its not a bug, it's a wrong design of app (assuming that `context` passed to `Fragment`s `onAttach` method will be always same as probably hosting `Activity`) – snachmsm Apr 20 '22 at 18:55
  • Try this solution https://stackoverflow.com/questions/32258125/onattachactivity-deprecated-where-i-can-check-if-the-activity-implements-call – Sandesh Khutal Apr 21 '22 at 07:23

1 Answers1

0

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.

Syed Faizan Ali
  • 361
  • 1
  • 8