【问题标题】:Check Firebase Child value in kotlin检查 kotlin 中的 Firebase Child 值
【发布时间】:2019-10-21 04:18:13
【问题描述】:

我正在尝试设置一个数据库应用程序,但我卡住了一会儿。

我希望每个人都能够将数据写入数据库,这是..如果一条信息已经存在,则不应覆盖数据。

例子:

  • A 人添加:cd-title + BandA
  • 数据库会将这些信息保存在两个孩子之下

    personA private --->
                 Cd-title, Band A
    
    Database --->
          Cd-title, Band A
    
  • B 人添加:cd-title + BandA

    personB private --->
                 Cd-title, Band A
    
    Database--->
         // error child already exists
    

代码方面应该像

get value. child
       if !=null
         error child already exists
       if = null
         info succesfully saved

   val ref = FirebaseDatabase.getInstance().getReference("/Wishlist/$uid/$album")

        val Vinyl_piece = Albumadd(aAlbum, bBand, nName, gGenre, bBuildyear, SideA1, SideA2, SideA3, SideA4, SideA5)

        ref.setValue(Vinyl_piece)

【问题讨论】:

    标签: firebase kotlin firebase-realtime-database


    【解决方案1】:

    如果您想根据同一位置的现有值(或缺少值)将值写入数据库,则需要use a Firebase Database transaction

    在你的情况下,它看起来像:

    postRef.runTransaction(object : Transaction.Handler {
        override fun doTransaction(mutableData: MutableData): Transaction.Result {
            if (mutableData.value == null) {
                // Set value and report transaction success
                mutableData.value = Vinyl_piece
            }
            return Transaction.success(mutableData)
        }
    
        override fun onComplete(
            databaseError: DatabaseError?,
            b: Boolean,
            dataSnapshot: DataSnapshot?
        ) {
            // Transaction completed
            Log.d(TAG, "runTransaction:onComplete:" + databaseError!!)
        }
    })
    

    【讨论】:

    • 我认为您缺少else
    猜你喜欢
    • 2021-12-25
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2020-03-25
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    相关资源
    最近更新 更多