[英]Android - How to add ListView item dynamically from other class
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. 我正在使用FCM(最新的GCM)开发简单的短信应用程序,其中有一个名为ChatActivity的活动,该活动使用ListView显示消息列表。
However, when any new message arrives it will be handled by FirebaseMessagingService class... 但是,当任何新消息到达时,它将由FirebaseMessagingService类处理。
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 ? 我的问题是,当我从onMessageReceived()类的FCM中收到新消息时,如何将该字符串消息添加到ChatActivity中的ListView中?
And, after adding item to the ListView, how can I call .notifyDataSetChanged() on ListView Adaptor ? 并且,将项目添加到ListView之后,如何在ListView Adapter上调用.notifyDataSetChanged()?
There are many ways you can pass data to an Activity and by extension a ListView upon receiving a message. 您可以通过多种方法将数据传递给Activity,并通过扩展将ListView接收到消息。 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. 一种简单的方法是在“活动”中设置一个BroadcastReceiver,然后在收到FCM消息时,可以使用LocalBroadcastManager发送广播,指示您的活动应更新ListView的适配器。 See LocalBroadcastManager for more. 有关更多信息,请参见LocalBroadcastManager 。
@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 . @McAwesomville建议您使用Firebase Realtime Database ,这也是一种选择,您可以在Firebase Android Codelab中将其用于简单的聊天应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.