Search code examples
androidfirebaseandroid-activityandroid-fragmentactivity

How to transfer data between fragment and non parent activity?


I am very struggling to solve this problem

enter image description here

I am listening data from conversation list fragment

Now how to send received data in chatting activity when chatting is going on? Please help.


Solution

  • If I undestood the problem correctly, this seems like a job for an EventBus. Have a look on how to implement it here : http://square.github.io/otto/

    First of all you need to define a event

    public class ChatMessage{
       private String status,message,sender;
       //with constructors and toString
    }
    

    In your Chatting activity you post the event on the event bus, something like this

    EventBus.getDefault().post(new ChatMessage(status,message,sender)
    

    In your Conversation list (assuming you're displaying with a List or Recyclerview managed by an adapter) , make the adapter aware of your event bus

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAdapter(ChatMessage message) {
        //here you should get the chat item and update it
        //do not forget to call notifyDatasetChanged() at the end to update your adapter
    }
    

    Post a message to the EventBus at anytime you want the Conversation list fragment to be updated(eg. when a message is incoming , when you are sending a message to a contact)

    If you can provide additional code form your fragments/activities and form the adapter I'll update my answer.