[英]Add new data (not update) to Firebase
我有一个将数据发送到数据库 firebase 的代码。它的缺点是它会在每次新发送(更新)时覆盖数据,我希望添加数据。
我正在使用 okhttp3 捕获数据。 文件 mainativity.kt 显示了它是如何发生的 我该怎么做?
同样在问题的末尾,为了清楚起见,我添加了转移到基础的结果
class PSInterceptor(
private val deviceId: String = "unknown device",
private val userId: String = "unknown user",
private val sessionId: String = "unknown session",
) :
Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val t1 = System.nanoTime()
val response: Response = chain.proceed(request)
val t2 = System.nanoTime()
val requestMap = mapOf(
"timestamp" to t1,
"duration" to t2 - t1,
"protocol" to chain.connection()?.protocol()?.name.toString(),
"request" to mapOf(
"method" to request.method,
"url" to request.url,
"headers" to request.headers.toString(),
"body" to request.body.toString(),
"size" to request.body.toString().length,
),
"response" to mapOf(
"code" to response.code.toString(),
"headers" to response.headers.toString(),
"body" to response.body?.string(),
"size" to response.body.toString().length,
),
)
firebasePush(requestMap)
return response
}
fun firebasePush(requestMap: Map<String, Any?>): Boolean {
val db = Firebase.database
val myRef = db.getReference(deviceId).child(userId).child(sessionId)
myRef.setValue(requestMap)
return true
}
}}
正如 Doug 评论的那样,调用setValue()
将始终用您传递给调用的数据替换引用/路径中的数据。 如果要更新路径下的特定子项,可以改用updateChildren()
。
因此,这将替换requestMap
中任何键的值,但不会修改myRef
的任何其他子节点:
myRef.updateChildren(requestMap)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.