I'm making an app that periodically uploads your step data to Firestore for tracking purposes, and I add all the step data with date:steps in key:value pairs of a hashmap, but for some reason, each individual key:value pair goes into a nested map as value with the key as some arbitrary number. I can't figure out why this is happening. Here's the code:
val stepMap = HashMap<String, String>()
for (dp in dataSet.dataPoints) {
Log.i(TAG,"Data point:")
Log.i(TAG,"\tType: ${dp.dataType.name}")
Log.i(TAG,"\tStart: ${dp.getStartTimeString()}")
Log.i(TAG,"\tEnd: ${dp.getEndTimeString()}")
for (field in dp.dataType.fields) {
Log.i(TAG,"\tField: ${field.name.toString()} Value: ${dp.getValue(field)}")
stepMap.put("${dp.getStartTimeString()}", "${dp.getValue(field)}")
}
}
db.collection("users")
.document("" GoogleSignIn.getLastSignedInAccount(this).email)
.update(LocalDateTime.now().toString(), stepMap)
This is what the data looks like on Firestore:
I need it to look like this: what it should look like
CodePudding user response:
Try =>
db.collection("users")
.document("" GoogleSignIn.getLastSignedInAccount(this).email)
.update(LocalDateTime.now().toString(), FieldValue.arrayUnion(stepMap))
CodePudding user response:
Assuming that you have a database structure that looks like this:
Firestore-root
|
--- users (collection)
|
--- $email (document)
|
--- UploadTime (Map)
|
--- StartTime1: "value1"
|
--- StartTime2: "value2"
|
--- StartTime3: "value3"
To update the values of StartTime1
, StartTime2
and StartTime3
that exist under the UploadTime
property, please use the following lines of code:
db.collection("users")
.document("" GoogleSignIn.getLastSignedInAccount(this).email)
.update(
"UploadTime.StartTime1", "value4",
"UploadTime.StartTime2", "value5",
"UploadTime.StartTime3", "value6"
).addOnCompleteListener(/* ... /*);
The result in your database will be:
Firestore-root
|
--- users (collection)
|
--- $email (document)
|
--- UploadTime (Map)
|
--- StartTime1: "value4"
|
--- StartTime2: "value5"
|
--- StartTime3: "value6"
Since it's an update operation, all the other fields in the document will remain untoched.