i started using OTTO by Square yesterday, so far i had a good start.
Otto works great out of the Box when you have your Fragments already hosted in an FragmentActivity and you just need communicate between Fragment hosted by that FragmentActivity.
When hosted already, your #onResume() Methode gets called and the Fragment can register itself on the Eventbus:
@Override
public void onResume()
{
super.onResume();
BusProvider.getInstance().register(this);
}
My Problem:
The Fragment which is embedded in an extra Activity which should recieve the Event via the Eventbus looks like this:
public AnotherFragmentHostedInSomeActivity extends Fragment
{
.....
@Subscribe
public void onSomethingHappend(final Event event)
{
final SomeObject deliveredObject = event.getSomeObject();
But it looks like things are still complicated when you want to call another activity hosting a Fragment like this Code there:
public class SomeFragmentSendingDataToAnotherFragment extends Fragment
{
...
private void sendData()
{
final Intent intent = new Intent(applicationContext, SomeActivity.class);
applicationContext.startActivity(intent);
BusProvider.getInstance().post(new Event(someObject));
As you might already see, this code is dodgy. Starting a Activity an then sending Data to the Fragment hosted by that Activity cant work because of the lifecycle. So the Activity get created and the Fragements also. At some time the onResume Methode gets called so the Fragement can register isself using @Subscribe. But this all happens after the event already got posted via the EventBus. So the Fragment of interrest never gets called by the EventBus.
Anyone knows how to do this in a smart way ?
Some extra Infos there: I had a nice playaround yesterday with OTTO. The Problem only aprears in my Project when i need to send Data to another Activity which is in my case happening always when the APP runs on an Smartphone, not an Tablet. Before i send all data via Intent and Parcelable. Otto would reduce the need writing Parcleable Objects so i would like to go this way.
Thanks for Answers
By the time the second Activity starts, your original Activity is gone. As others have pointed out, if you want to pass data from Activity to Activity, using Intents is probably the best route.
If you really want an event bus, you need an object that stays alive even after the first activity goes away. In Android, this is something tied to the Application context or if using Dagger or Guice, a @Singleton.
This singleton is where you use Otto's @Produce annotation. When the second Activity subscribes to the bus, it will receive any data from that @Produce method.