Home > Software engineering >  Add new data (not update) to Firebase
Add new data (not update) to Firebase

Time:04-18

I have a code that sends data to DataBase firebase. Its disadvantage is that it overwrites the data with each new send (update), and I would like the data to be added.

I am capturing data with okhttp3. File mainativity.kt shows how it happens How can I do that?

Also at the end of the question, for clarity, I added the result that is transferred to the base

    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
    }
}}

CodePudding user response:

As Doug commented, calling setValue() will always replace the data at the reference/path with the data you pass to the call. If you want to update specific children under the path, you can use updateChildren() instead.

So this will replace the values of any keys in your requestMap, but will leave any other child nodes of myRef unmodified:

myRef.updateChildren(requestMap)
  • Related