EventBus Demo


Source link: https://github.com/Morxander/TestingEventBus

TestingEventBus

You can read this article on my Blog

I started to use EventBus library of greenrobot and I wanted to share it with you. EventBus is a publish/subscribe event bus optimized for Android according to the description in the readme file on their repo. In other word it's a Bus for events to transfer the data between your application classes. I am using MVP as a design pattern for my apps but I will just show how to work with the EventBus library on an empty Android Project so every time I'll mention the Activity It will be your Presenter if you're using MVP like me. Also I created a github repo with an example project and you will find its link on the end of this article.

Create a new Android project

create a new Android project and add the following line to the app gradle file :

compile 'org.greenrobot:eventbus:3.0.0' 

That's how you tell Android Studio to download the EventBus library and include it to your project.

Set the UI of the MainActivity

Open the activity_main.xml file and add the following lines in it.

<TextView
  android:id="@+id/mainactivity_textview"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center"
  android:layout_marginTop="20dp"
  android:textSize="25sp"
  android:text="The message will be here" />  <Button
  android:id="@+id/mainactivity_button"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="20dp"
  android:text="Go To Next Activity"/> 

Then your edit the MainActivity class to be like this public class MainActivity extends AppCompatActivity {


 TextView mainActivityTextView;
  Button mainActivityButton;

@Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  // init the views  mainActivityTextView = (TextView) findViewById(R.id.mainactivity_textview);
  mainActivityButton = (Button) findViewById(R.id.mainactivity_button);
 
}
 

Create the ChildActivity

Create a new activity called ChildActivity.

XML :

<EditText
  android:id="@+id/childactivity_edittext"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center"
  android:layout_marginTop="20dp"
  android:textSize="25sp"
  />  <Button
  android:id="@+id/childactivity_button"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="20dp"
  android:text="Send To Main Activity"/> 

Java :

@Override protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_child);

  // init the views
  childActivityEditText = (EditText) findViewById(R.id.childactivity_edittext);

  childActivityButton = (Button) findViewById(R.id.childactivity_button);
 
}
 

Create the Message class

We have to create a class for the message which will be transfered between our activities and you have the freedom to call it whatever you like and to have any method, In this case we will call it MessageEvent and we will put a String var called message and set a getter&setter for it.

public class MessageEvent {

  private String message;

public String getMessage() {

return message;
  
}

public void setMessage(String message) {

this.message = message;
  
}
 
}
 

Register your MainActivity to the EventBus

You have to register your activity to the EventBus you have to put this like in the onCreate method :

EventBus.getDefault().register(this);
 

and to understand it, the EventBus class is a Singleton class and the getDefault() is a static method which returns the instance of this class. also the register() is the method which register the views/class to the EventBus and we pass the mainactivity object to it.

Now your MainActivity is registered but how to pick up the call when the EventBus publish the event? just create a onMessageEvent method and use the @Subscribe annotation above it.

@Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent messageEvent){

  mainActivityTextView.setText(messageEvent.getMessage());
 
}
 

And now every time the EventBus will publish the MessageEvent you activity will know about it.

Post the message to the EventBus

On your ChildActivity put this code


 childActivityButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

 MessageEvent messageEvent = new MessageEvent();

 messageEvent.setMessage(childActivityEditText.getText().toString());

  EventBus.getDefault().post(messageEvent);

}

  
}
);
 

which is just creating a new object of MessageEvent and uses the post() method of the EventBus to tell it to publish the new MessageEvent object to whoever cares about it.

Why to use EventBus?

It will help you to apply the publisher/subscriber pattern without getting your hand dirty with the details, and of course they already took care of the performance and the optimizations for you, so don't reinvent the wheel.

Example

I create a Github repo to be an example for you : https://github.com/Morxander/TestingEventBus

I welcome any suggestion or advices about what I wrote here on this article :)

Resources

A small library containing two adapters which allow for easy fragment management with a NavigationView.

Custom view for user input that models horizontal wheel controller.

Quill is the beautiful Android app for your Ghost blog.

Spotlight is a android library to onboard user by showcasing specific features in the app.

More easy way to add multiple delegates to your expandable RecyclerView.

A library which extends Android layouts to allow for the easy configuring of gradient backgrounds.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes