【问题标题】:How to store firestore's new Timestamp object type in android's local database Room?如何将firestore的新Timestamp对象类型存储在android的本地数据库Room中?
【发布时间】:2019-02-27 17:03:35
【问题描述】:

我使用最近在 Firestore 中引入的新对象类型(位于 Timestamp)将日期存储在 Firestore 中。我想将这些相同的 Timestamp 对象存储在我的 SQLite 驱动的Room 中。

据我所知,目前 Room 不支持时间戳。但它支持 TypeConverter。

是否有任何 TypeConverter 可用于转换时间戳。我担心的是避免在我的代码中对 Firestore 和 Room 进行两种不同的日期转换。但由于存在限制,我不介意在 Room 中存储时使用 TypeConverter 来回转换。这样我仍然可以在代码级别使用时间戳。

谢谢,

【问题讨论】:

    标签: android sqlite google-cloud-firestore android-room


    【解决方案1】:

    Timestamp 对象只包含两个整数值 - 自 unix 纪元以来的秒数,以及添加到其中的秒数(以纳秒为单位)。如果您不需要纳秒的极端精度,您可以只存储自纪元值以来的秒数,并假设小数部分为 0。

    如果您确实需要这两个值,那么您需要将它们映射到 sqlite 中的两个不同列。

    据我所知,目前还没有软件可以为您执行此操作,但实现此功能应该很简单。

    【讨论】:

      【解决方案2】:

      TypeConverter 将无法映射两列(它只能转换为 StringDate 表示形式);可以使用下面的类TimeStamp,以及另一个@Entity 中的@Embedded 注释。而我只是想知道,是否必须为该类声明tableName

      // @Entity(tableName = "tableName")
      class TimeStamp {
      
          @ColumnInfo(name = "seconds")
          private long seconds = 0;
      
          @ColumnInfo(name = "nanoseconds")
          private Integer nanoseconds = 0;       
      
          public Timestamp() {}
      
          @Ignore
          public Timestamp(long s, @Nullable Integer ns) {
              this.setSeconds(s);
              this.setNanoSeconds(ns);
          }
      
          public void setSeconds(long s) {
              if(s < 0) {s = 0;}
              this.seconds = s;
          }
      
          public void setNanoSeconds(@Nullable Integer ns) {
              if(ns == null || ns < 0) {ns = 0;}
              this.nanoseconds = ns;
          }
      
          public long getSeconds() {
              return this.seconds;
          }
      
          public long getMilliSeconds() {
              return (this.seconds * 1000);
          }
      
          public int getNanoSeconds() {
              return (int) this.nanoseconds;
          }
      
          public Date toDate() {
              return new Date(this.getMilliSeconds());
          }
      
          public String toString() {
              return String.valueOf(this.seconds) + "." + String.valueOf(this.nanoseconds);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-21
        • 2017-11-27
        • 1970-01-01
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-05
        相关资源
        最近更新 更多