Java – Using Otto to pass data from an activity to an activity does not work

Using Otto to pass data from an activity to an activity does not work… here is a solution to the problem.

Using Otto to pass data from an activity to an activity does not work

This is my first time using this library, but I’ve been following this video tutorial for sending data via fragments, but in my case, it just is Activities.. So that’s how I did it

I’m sending data to the activity :

public void onClick(View view) {
    String passing_data = new Gson().toJson(user);
    BusStation.getBus().post(new MessageData(passing_data));
    Intent intent = new Intent(activity,UserAdsView.class);
    activity.startActivity(intent);
}

BusStation class:

public class BusStation {
    private static Bus bus = new Bus();

public static Bus getBus() {
        return bus;
    }
}

Message data class:

public class MessageData {
    private String msgData;

public MessageData(String msgData) {
        this.msgData = msgData;
    }

public String getMsgData() {
        return msgData;
    }
}

Finally, there is the UserAdsView activity:

@Override
protected void onResume() {
    super.onResume();
    BusStation.getBus().register(this);
}

@Override
protected void onPause() {
    super.onPause();
    BusStation.getBus().unregister(this);
}

@Subscribe
public void recievedData(MessageData messageData){
    target = messageData.getMsgData();
    Toast.makeText(getApplicationContext(), target, Toast.LENGTH_SHORT).show();
}

As described in the video, this method should be triggered recievedData!

Solution

When you sent the notification in the first activity at that time, the UserAdsView activity was not registered and therefore there was no event listener.

In this line

 BusStation.getBus().post(new MessageData(passing_data));

You are sending notifications, but you are not registered to receive them. That is, the UserAdsView activity has not yet started.

If you need to pass data to activity at launch time, simply send it via
Intent.

Related Problems and Solutions