向 Firebase 添加新数据(不是更新)

Add new data (not update) to Firebase

我有一个代码可以将数据发送到 DataBase 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() 将始终用您传递给调用的数据替换 reference/path 中的数据。如果要更新路径下的特定子项,可以使用 updateChildren() 代替。

所以这将替换您 requestMap 中任何键的值,但会使 myRef 的任何其他子节点保持不变:

myRef.updateChildren(requestMap)