将对象添加到继承FirebaseMessagingService继承服务(FCM)的类的realm数据库

时间:2018-04-17 06:51:32

标签: java android realm firebase-cloud-messaging

大家好我在公共构造函数(onMessageReceived)FirebaseMessagingService下面调用下面的方法(SaveMessage)来保存领域中的字符串但是在从这个表中获取日期后得到通知它的空白

   public class FireBaseService extends FirebaseMessagingService {


    public static  int NOTIFICATION_ID = 1;
    Handler handler;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    generateNotification(remoteMessage.getNotification().getBody(),remoteMessage.getNotification().getTitle());

    SaveMessage(remoteMessage.getNotification().getBody());
    //AddList(remoteMessage.getData().get("message"));
    //StartActvity(Integer.valueOf(remoteMessage.getData().get("key_1")));

  }

 public void SaveMessage(final String message){


           Realm realm = Realm.getDefaultInstance();
               realm.executeTransactionAsync(new Realm.Transaction() {
                   @Override
                   public void execute(Realm realm) {
                       SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
                       String strTime = simpleDateFormatTime.format(new Date());
                       Number currentIdNum = realm.where(MessagePojo.class).max("id");

                       int nextId;
                       if (currentIdNum == null) {
                           nextId = 1;
                       } else {
                           nextId = currentIdNum.intValue() + 1;
                       }
                       MessagePojo messagePojo =  realm.createObject(MessagePojo.class,nextId);
                       messagePojo.setDate(strTime);
                       messagePojo.setMessage(message);
                       realm.insertOrUpdate(messagePojo); 
                       EventBus.getDefault().postSticky(true);
                       realm.close();
                   }
               });


}
}

并在一个片段中为此Realm表添加更改侦听器。

谢谢你的阅读。

1 个答案:

答案 0 :(得分:0)

最后我用handler和looper以及RealmChangeListener工作perefect来解决它:

[
 {id: 1, name: 'jhon'},
 {id: 2, name: 'max'},
 {id: 3, name: 'fer'}
]