简体   繁体   中英

How to use Firebase's ServerValue.TIMESTAMP as a child and set a value to it

I want to create a structure like

"child1/1510612788766/": key: "quantity", value: 10
"child1/1510612788767/": key: "quantity", value: 4
"child1/1510612788768/": key: "quantity", value: 1
"child2/1510612788710/": key: "quantity", value: 6
"child2/1510612788756/": key: "quantity", value: 8

but when I try:

ref.child("child1").child(ServerValue.TIMESTAMP);

there is a compilation error on the second child call:

Error:(59, 52) error: incompatible types: Map<String,String> cannot be converted to String

I know that this error is because the method expects a Map<String, Object> map instead of Map of timestamp.

But how could I store the ServerValue this way and set a value to it?

This isn't how ServerValue.TIMESTAMP is meant to be used.

child() takes a String with the name of the child you want to access. This is the name of a node in the database. It can only be referenced as a string, even if it's formatted as a number.

ServerValue.TIMESTAMP is a special (Map) value that you can use where you want to insert the server's sense of current time when adding or updating child data inside a node. It can't be used for the name of the node itself.

If you want to create a location of the database that's based on some time, you need to know what that time is before you start accessing it. ServerValue.TIMESTAMP won't help you with that, since it's a only generated on the server.

If you want to add data ordered by time, you should instead push() data into the database. The push id is based on time, but it is the client's sense of time, not the server.

If you REALLY need to use the server's sense of time in the name of a node, you should instead be using Cloud Functions for Firebase to measure time on Google servers and generate the path that you want to write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM