【问题标题】:@ServerTimestamp is allways null on Firebase Firestore@ServerTimestamp 在 Firebase Firestore 上始终为空
【发布时间】:2018-02-22 13:14:36
【问题描述】:

这是我的模型类:

import com.google.firebase.firestore.ServerTimestamp;
import java.util.Date;

        public class YourModelClass {
            private @ServerTimestamp Date timestamp;

            YourModelClass() {}

            public Date getTimestamp() {
                return timestamp;
            }

            public void setTimestamp(Date timestamp) {
                this.timestamp = timestamp;
            }

            @Override
            public String toString() {
                return "YourModelClass{" +
                        "timestamp=" + timestamp +
                        '}';
            }
        }

当我在 Log 中打印时,我得到了 null

    Logger.info("Date", new YourModelClass()+"------"+new YourModelClass().getTimestamp() + "");

这是错误:

Output: 02-22 18:33:12.066 18980-18980/com.spendeye I/Date: YourModelClass{timestamp=null}------null

请告诉我解决方案。

【问题讨论】:

  • 你能发布你用来上传服务器时间到firebase的代码吗?而且,在您的 firebase 数据库中,名称与您的 POJO 相同吗?这很重要

标签: java android firebase google-cloud-firestore


【解决方案1】:

这不是从数据库中检索日期的正确方法。假设您正在使用get() 调用,当检索date 作为Date 类类型的对象时,您需要使用以下代码:

Date date = yourModelClass.getDate();
DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US); //Or any other locale
String creationDate = dateFormat.format(date);
Log.d("TAG", creationDate);

如您所见,我使用的是从数据库中获取的格式化日期,而不是创建类的新实例。您也可以在我的一个 tutorials 中看到这种方法,我在其中逐步解释了如何添加和显示日期。

【讨论】:

    【解决方案2】:

    如果您在将日志存储到 Firestore 之前打印日志,那么在保存到 Firestore 之前,任何类中的属性 timestamp@ServerTimestamp 的值始终为空。

    因此你得到 null

    如果您可以删除日志语句并让对象保存在 Firestore 上,那么当您从 Firestore 取回该类对象时,日志语句会有所不同,不会显示 null。 p>

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2020-06-16
      • 2020-01-16
      • 2020-06-06
      相关资源
      最近更新 更多