I am new to Android, and trying to send message from a Fragment to its container Activity using EventBus. However, I am getting error:
D/EventBus: No subscribers registered for event class com.app.todo.controllers.task.TaskListFragment$TaskCreateSelectEvent
Following is the code in Activity class related to EventBus:
public class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onTaskCreateSelectEvent(event: TaskListFragment.TaskCreateSelectEvent) {
Log.d("TAG", "On Main Activity")
}
fun addFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit)
transaction.add(R.id.task_fragment_container, fragment)
transaction.addToBackStack(fragment.javaClass.simpleName)
transaction.commit()
}
public override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
public override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
}
Following is in Fragment class
public class TaskListFragment : Fragment() {
private var fab: FloatingActionButton? = null
public class TaskCreateSelectEvent {
var fab: FloatingActionButton? = null
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var view = inflater!!.inflate(R.layout.task_list_fragment, container, false)
fab = view.findViewById<FloatingActionButton>(R.id.fab)
fab!!.setOnClickListener {
val selectEvent = TaskCreateSelectEvent()
EventBus.getDefault().post(selectEvent)
}
return view
}
}
This is how library is added in build.gradle
file.
apply plugin: 'kotlin-kapt'
dependencies {
compile 'org.greenrobot:eventbus:3.0.0'
kapt 'org.greenrobot:eventbus-annotation-processor:3.0.1' }
kapt {
arguments {
arg('eventBusIndex', 'com.app.todo.controllers.MyEventBusIndex')
}
}
Any idea what I am doing wrong?
EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.
An event bus is a pipeline that receives events. Rules associated with the event bus evaluate events as they arrive. Each rule checks whether an event matches the rule's criteria. You associate a rule with a specific event bus, so the rule only applies to events received by that event bus.
I am new to Android ...
then you should better get familiar with dagger and rx instead. Event busses are a bad thing on android and often make things more complicated than necessary.
https://www.google.de/search?q=android+rxjava+instead+of+eventbus
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With