0

I am developing simple text messaging app using FCM (latest GCM), where I have an activity called ChatActivity that shows list of messages using ListView.

However, when any new message arrives it will be handled by FirebaseMessagingService class...

public class MyFcmListenerService extends FirebaseMessagingService {

    @override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String from = remoteMessage.getFrom();
        Map<String, String> data = remoteMessage.getData();
        String body = rawData.get("body");

        Log.i("From",from);
        Log.i("Message",body);

    }
}

This class prints message in console successfully whenever any new message arrives.

My question is, when I get a new message from FCM in onMessageReceived() class, how can I add that String message to the ListView in ChatActivity ?

And, after adding item to the ListView, how can I call .notifyDataSetChanged() on ListView Adaptor ?

Amit Tank
  • 67
  • 1
  • 9
  • Just curious. Is there any reason as to why you're not using Firebase`s real-time database for your chat app? Based from your use case, it's easier to implement. – AL. Jun 03 '16 at 02:26
  • On a more related note, technically, this is just like [passing data from Service to Activity](http://stackoverflow.com/questions/14351674/send-data-from-service-to-activity-android). – AL. Jun 03 '16 at 02:47

2 Answers2

0

There are many ways you can pass data to an Activity and by extension a ListView upon receiving a message. One simple way is to set up a BroadcastReceiver in your Activity and then when you receive your FCM message you can use LocalBroadcastManager to send a broadcast indicating that your activity should update the ListView's adapter. See LocalBroadcastManager for more.

@McAwesomville suggests using Firebase Realtime Database, is also an option, you can see it in use for a simple chat app in the Firebase Android Codelab.

Arthur Thompson
  • 9,087
  • 4
  • 29
  • 33
0

I am using FirebaseUI in my app and it works very well. You can read more about it here.

Riley MacDonald
  • 453
  • 1
  • 4
  • 15