androidfirebasekotlinfirebase-realtime-databaseandroid-room

how to backup Room Entity with Date datatype to Firebase Realtime Database (Kotlin)


I need to send a copy of my Room Database table to the Firebase Realtime Database, but it didn't work when having date datatype on my room database. I am using Kotlin and Android Studio. please, I need a clear way to send a list of objects that have a date datatype from Room to Firebase Realtime Database.

Here is the structure of my data


@Entity
data class Bill(
   @PrimaryKey
    val id:Date,
    var name:String,
    var category: String,
    var price:Long,
    var count:Int,
    var total:Long,
    var date: LocalDate
)

I have a reference on firebase having the same variables but don't know what datatype to choose for id and date variables or how to convert from room to be accepted in firebase realtime database.

I searched a lot and didn't find a clear structure of how to solve it. I know that firebase database doesn't accept date datatype but I am expecting there is a way to convert date type when sending to firebase. I am sending it as a full List of objects not an object.

thanks


Solution

  • I don't know what datatype to choose for the id and date variables or how to convert from room to be accepted in the Firebase Realtime Database.

    Unfortunately, the Date and the LocalDate are not supported data types in the Firebase Realtime Database. What you can use instead is a ServerValue#TIMESTAMP as explained in my answer from the following post:

    Or any other Unix timestamp value which represents the time since the Unix epoch, in milliseconds.

    Edit:

    There is no way you can generate a timestamp client-side. Remember that FieldValue values are just tokens that are interpreted on the Firebase server. So when using Firestore, you can use a Date object instead. So you can save all the operations to Room and then synchronize the data at the end of the day with Firestore.

    I'm not sure why would you implement such a mechanism, I would go ahead with saving the data from the first time in the Cloud.