Monday, August 12, 2019

How to pass data Activity to Activity in Android use Event Bus otto

Today I use a method of  pass data in android eventbus Otto, to perform sending data from Activity to Activity in Android, here are the steps to send data in Android.
How to pass data Activity to Activity in Android use Event Bus otto

Step 1. Creat clss EventBus.class
package com.example.eventbus.model;
import com.squareup.otto.Bus;
public class EventBus {
    private static Bus sBus;
    public static Bus getBus() {
        if (sBus == null)
            sBus = new Bus();        return sBus;    }
}

Step 2. Create event mesage
package com.example.eventbus.model;
public class MessageEvent {
    public String mMessage;
    public MessageEvent(String message) {
        mMessage = message;    }

    public String getMessage() {
        return mMessage;    }
}

Step 3. Create layout 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"    tools:context=".MainActivity">    <Button        android:id="@+id/btn_click"        android:text="Second"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
    <TextView        android:id="@+id/tv_message"        android:layout_marginTop="20dp"        android:padding="10dp"        android:textColor="#000"        android:textSize="20dp"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
</LinearLayout>

Step 4. Create second_acitivity.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">    <Button        android:id="@+id/btnSendData"        android:layout_width="match_parent"        android:text="Send"        android:layout_height="wrap_content" />
</LinearLayout>

Step 5. Register Event in MainActivity
EventBus.getBus().register(this);
Step 6. Unregister,xml
@Overrideprotected void onStop() {
    super.onStop();    EventBus.getBus().unregister(this);}
Step 7. Regiter and listnengEvent in SecondActivity.xml
 @Subscribe
    public void getMessage(MessageEvent event) {
        Toast.makeText(this, "" + event.getMessage(), Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getBus().register(this);
    }
    @Override
    protected void onStop() {
        super.onStop();
    }
you can download project at github

No comments:

Post a Comment