androidevent-busgreenrobot-eventbusgreenrobot-eventbus-3.0

How can an AppCompatActivity communicate with FragmentActivity using the EventBus?


Question, How can an AppCompatActivity communicate with FragmentActivity using the EventBus?

Findings, FragmentActivity can communicate with AppCompatActivity and the onEvent method is called, but if we switch the communication path to AppCompatActivity communicates with FragmentActivity, the onEvent method is never called.

public class MainActivity extends AppCompatActivity{
 private String data;
 @Override protected void onCreate{
  data = "private String data from MainActivity";
  EventBus.getDefault().postSticky(data);
 }
}

public class AccountFade extends FragmentActivity{
 private String mAccountFadeData;
 @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
 public void onEvent(String s){
  Toast.makeText(this, "private String mAccountFadeData from MainActivity", Toast.LENGTH_LONG).show();
  this.mAccountFadeData = s;
 }

 @Override protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  EventBus.getDefault().register(this);
 }

 @Override public void onDestroy(){
  EventBus.getDefault().unregister(this);
  super.onDestroy();
 }
}

Solution

  • You must create class that contain one String variable and fire that class by EventBus.

    So first create class like this

    public class DataChangeEvent {
        private String data;
    
        public DataChangeEvent(String data) {
            this.data = data;
        }
    
        public String getData() {
            return data;
        }
    
        public void setData(String data) {
            this.data = data;
        }
    }
    

    Now use this for your event

    Post in Activtiy :

     EventBus.getDefault().postSticky(new DataChangeEvent(data));
    

    Get in FragmentActivity :

     @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
     public void onEvent(DataChangeEvent event){
          Toast.makeText(this, "private String mAccountFadeData from MainActivity", Toast.LENGTH_LONG).show();
          this.mAccountFadeData = event.getData();
     }