(Tutorial Android) Passing Object Using Greenrobot Eventbus


EventBus ialah library open source untu Android yang memungkinkan komunikasi antara komponen dengan teknik publisher/subscriber. Dengan memakai EventBust, kita sanggup mengirim data atau objek dari kelas satu ke kelas lainnya hanya dengan beberapa baris aba-aba saja. Selain itu juga memudahkan komunikasi antara Activity, Fragment, Thread dan Services.



Beberapa laba memakai EventBus :
- Membuat komunikasi antar komponen menjadi sederhana
- Cepat
- Ukuran library kecil (<50k)
- Terbukti dan digunakan oleh banyak aplikasi menyerupai WhatsApp
- Memiliki fitur yang canggih menyerupai delivery thread, subcriber prioritas dan lain-lain.

Pada kesempatan kali ini, aku akan menciptakan tutorial sederhana dengan library EventBus. Penggunaan EventBus sangat gampang yaitu hanya perlu register sebuah kelas kemudian mengirimkan objek ke tujuan. Lalu dari tujuan tinggal memanggil subcribe saja.

Langsung saja ke TKP.

Tambahkan dependencies di module-level gradle.
compile 'org.greenrobot:eventbus:3.0.0' 

Disini aku memakai EventBus versi 3. Latest version sanggup dilihat di http://greenrobot.org/eventbus/

Buat 2 buah layout diantaranya activity_main dan activity_edit.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context="com.example.wim.android_eventbus.MainActivity">          <TextView             android:id="@+id/username"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="Username"/>          <TextView             android:id="@+id/realname"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="Realname"             android:layout_marginTop="10dp" />          <TextView             android:id="@+id/phone"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_marginTop="10dp"             android:text="Phone"/>          <TextView             android:id="@+id/aboutme"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="About Me"             android:layout_marginTop="10dp" />          <Button             android:id="@+id/btnEdit"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_gravity="center"             android:layout_marginTop="20dp"             android:text="Edit Profile" />   </LinearLayout>  
activity_edit.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="@dimen/activity_horizontal_margin">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_centerInParent="true"         android:orientation="vertical">          <EditText             android:id="@+id/txtUsername"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginTop="10dp"             android:hint="Username" />          <EditText             android:id="@+id/txtRealname"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginTop="10dp"             android:hint="Realname" />           <EditText             android:id="@+id/txtPhone"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginTop="10dp"             android:inputType="phone"             android:hint="Phone Number" />           <EditText             android:id="@+id/txtAboutMe"             android:layout_width="match_parent"             android:layout_height="100dp"             android:layout_marginTop="10dp"             android:gravity="top"             android:hint="About Me" />          <Button             android:id="@+id/btnSave"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_gravity="center"             android:layout_marginTop="20dp"             android:text="Save" />     </LinearLayout>  </LinearLayout> 

Setelah itu buat kelas dengan nama User. Kelas User nantinya akan kita jadikan objek yang akan di kirimkan antar activity.
package com.example.wim.android_eventbus.model;  /**  * Created by wim on 5/19/16.  */ public class User {      private String username;     private String realname;     private String phone;     private String aboutme;      public User() {     }      public String getUsername() {         return username;     }      public void setUsername(String username) {         this.username = username;     }      public String getRealname() {         return realname;     }      public void setRealname(String realname) {         this.realname = realname;     }      public String getPhone() {         return phone;     }      public void setPhone(String phone) {         this.phone = phone;     }      public String getAboutme() {         return aboutme;     }      public void setAboutme(String aboutme) {         this.aboutme = aboutme;     } }  

Untuk penggunaan EventBus hanya perlu meregistrasikan sebuah objek. Cara pemanggilannya menyerupai berikut :
EventBus.getDefault().register(this); 
Jika tidak ingin objek berada di EventBus lagi, tinggal unregister saja dengan cara berikut :
EventBus.getDefault().unregister(this); 
Untuk mengirim/post suatu event dari bab mana saja di aplikasi Android, cukup dengan memanggil method post(). Maka otomatis objek/event akan dikirimkan ke subcriber.
EventBus.getDefault().post(user); 
Nah terakhir untuk menangani setiap respon dari event/objek yang post yaitu dengan mendefinisikan method dibawah annotation @Subscribe.
@Subscribe public void onMessageEvent(User user){     if(user != null){         username.setText("Username : "+user.getUsername());         realname.setText("Realname : "+user.getRealname());         phone.setText("Phone Number : "+user.getPhone());         aboutme.setText("About Me : "+user.getAboutme());     }     Toast.makeText(this, "Data Updated!", Toast.LENGTH_SHORT).show(); } 
*Perlu di perhatikan bahwa di EventBus 3 kita bebas memberi nama method subscribe. Pada teladan di atas aku memberi nama method onMessageEvent() untuk menangani respon yang di post.

Selanjutnya buat activity dengan nama MainActivity. Disini MainActivity bertindak sebagai subsciber.
package com.example.wim.android_eventbus;  import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast;  import com.example.wim.android_eventbus.model.User;  import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe;  public class MainActivity extends AppCompatActivity implements View.OnClickListener{      private TextView username, realname, phone, aboutme;     private Button btnEdit;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          username = (TextView) findViewById(R.id.username);         realname = (TextView) findViewById(R.id.realname);         phone = (TextView) findViewById(R.id.phone);         aboutme = (TextView) findViewById(R.id.aboutme);          btnEdit = (Button) findViewById(R.id.btnEdit);          btnEdit.setOnClickListener(this);          User user = new User();         user.setUsername("andronut");         user.setRealname("Wim Sonevel");         user.setPhone("088888888888");         user.setAboutme("Hello Everyone! I'm Android Developer");          username.setText("Username : "+user.getUsername());         realname.setText("Realname : "+user.getRealname());         phone.setText("Phone Number : "+user.getPhone());         aboutme.setText("About Me : "+user.getAboutme());          // Register EventBus         EventBus.getDefault().register(this);     }      @Subscribe     public void onMessageEvent(User user){         if(user != null){             username.setText("Username : "+user.getUsername());             realname.setText("Realname : "+user.getRealname());             phone.setText("Phone Number : "+user.getPhone());             aboutme.setText("About Me : "+user.getAboutme());         }          Toast.makeText(this, "Data Updated!", Toast.LENGTH_SHORT).show();     }      @Override     public void onClick(View v) {         switch (v.getId()){             case R.id.btnEdit:                 EditActivity.start(this);                 break;         }     }      @Override     protected void onDestroy() {         super.onDestroy();          // Unregister EventBus         EventBus.getDefault().unregister(this);     } }  

Kemudian buat satu activity lagi dengan nama EditActivity. Event/objek akan dikirimkan lewat EditActivity.
package com.example.wim.android_eventbus;  import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText;  import com.example.wim.android_eventbus.model.User;  import org.greenrobot.eventbus.EventBus;  /**  * Created by wim on 5/19/16.  */ public class EditActivity extends AppCompatActivity implements View.OnClickListener{      private Button btnSave;     private EditText username, realname, phone, about;      public static void start(Context context){         Intent intent = new Intent(context, EditActivity.class);         context.startActivity(intent);     }      @Override     protected void onCreate(@Nullable Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_edit);          username = (EditText) findViewById(R.id.txtUsername);         realname = (EditText) findViewById(R.id.txtRealname);         phone = (EditText) findViewById(R.id.txtPhone);         about = (EditText) findViewById(R.id.txtAboutMe);          btnSave = (Button) findViewById(R.id.btnSave);         btnSave.setOnClickListener(this);     }      @Override     public void onClick(View v) {         switch (v.getId()){             case R.id.btnSave:                 User user = new User();                 user.setUsername(username.getText().toString());                 user.setRealname(realname.getText().toString());                 user.setPhone(phone.getText().toString());                 user.setAboutme(about.getText().toString());                  // Post                 EventBus.getDefault().post(user);                  finish();                 break;         }     }      @Override     protected void onDestroy() {         super.onDestroy();     }  }  

Selesai dan jalankan balasannya :

Sebelum di edit

Edit profile

Setelah di edit

Source code lengkap sanggup dilihat di https://github.com/andronut/Android-EventBus

Sekian dan supaya bermanfaat.
Happy Coding :)

Comments

Popular posts from this blog

Tugas Komplemen Terakhir

Transmisi Data

Konsep Oop Encapsulation