个性化阅读
专注于IT技术分析

Firebase:实时数据库更新和删除

本文概述

在上一节中, 我们学习了如何在数据库中读取和写入数据。现在, 我们将学习如何修改和删除数据库中的数据。

更新资料

为了更新JSON数据库中的单个节点, 我们只需在正确的子引用上使用setValue()即可。

correct child reference. 
myRef.setValue("Hello, World")
myRef.child("someChild").child("name").setValue(name)

如果我们要写入节点的特定子节点而不覆盖其他子节点, 则可以使用updateChildren()方法。当我们调用updateChildren()时, 可以通过指定键的路径来更新较低级别的子值。

例如

//writeNewPost function for chat application
private fun Newpost(userId:String, username:String, title:String, body:String){
	//creating new post at /user-posts/$userid/$postid simultaneously
	//Using push key
	val key=database.child("posts").push().key
	//Checking it is null or not
if(key==null){
		Log.w(TAG, "Could not get push key for posts")
		return
	}
	//Creating Post object
	val post=Post(userId, username, title, body)
	//Push it to a map
val postValues=post.toMap()
	val childUpdates=HashMap<String, Any>()
	childUpdates["/posts/$key"]=postValues
	childUpdates["/user-posts/$userId/$key"]=postValues
	database.updateChildren(childUpdates)
}

push()方法用于在/ posts / $ postid中为所有用户创建包含post的节点中的post, 并同时使用getKey()方法检索密钥。然后, 该密钥用于在用户帖子/ user-posts / $ userid / $ postid中创建第二个条目。使用/ user-posts / $ userid / $ postid路径, 我们可以通过一次调用updateChildren()同时更新到JSON树中的多个位置。以原子方式进行更新意味着所有更新成功或所有更新失败。

添加完成回调

如果我们想知道何时提交数据, 则可以添加完成监听器。 setValue()和updateChildren()都采用可选的完成侦听器。当写入成功提交到数据库后, 它将被调用。如果调用失败, 则向侦听器传递一个错误对象。此错误对象指示失败发生的原因。

database.child("users").child(userId).setValue(user)
	.addOnSuccessListener{
		//Write was successful!
		//?.
	}
.addOnFailureListener{
		//Write failed
		//?
}

删除

删除数据的最简单方法是在对数据位置的引用上调用removeValue()。我们还可以通过将null指定为另一个写操作(例如setValue()或updateChildren())的值来删除数据。我们可以将此技术与updateChildren()结合使用, 以在单个API调用中删除多个子级。

activity_upd_del.xml

upd_del.kt

package com.example.firebaserealtimedatabase

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_upd_del.*
import kotlinx.android.synthetic.main.activity_welcome.*
import kotlinx.android.synthetic.main.activity_welcome.email

class upd_del : AppCompatActivity() {

    private var mFirebaseDatabase: DatabaseReference? = null
        private var mFirebaseInstance: FirebaseDatabase? = null

        private var userId: String? = null

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_upd_del)

            mFirebaseInstance = FirebaseDatabase.getInstance()

            // get reference to 'users' node
            mFirebaseDatabase = mFirebaseInstance!!.getReference("users")

            val user = FirebaseAuth.getInstance().getCurrentUser()

            // add it only if it is not saved to database
            userId = user?.getUid()

        }


        private fun updateUser(name: String, email: String) {
            // updating the user via child nodes
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email)) {
                mFirebaseDatabase!!.child(userId!!).child("name").setValue(name)
                mFirebaseDatabase!!.child(userId!!).child("email").setValue(email)
                Toast.makeText(applicationContext, "Successfully updated user", Toast.LENGTH_SHORT).show()
            }
            else
                Toast.makeText(applicationContext, "Unable to update user", Toast.LENGTH_SHORT).show()

        }

        fun onUpdateClicked(view: View) {
            val name = name.getText().toString()
            val email = email.getText().toString()

            //Calling updateUser function 
            updateUser(name, email)
        }

        fun onDeleteClicked(view: View) {
            //Remove value from child 
            mFirebaseDatabase!!.child(userId!!).removeValue()
            Toast.makeText(applicationContext, "Successfully deleted user", Toast.LENGTH_SHORT).show()

            // clear information
            txt_user.setText("")
            email.setText("")
            name.setText("")
        }

        companion object {
            private val TAG = upd_del::class.java.getSimpleName()
        }
    }

输出量

Firebase:实时数据库更新和删除

更新之前

Firebase:实时数据库更新和删除

更新后

Firebase:实时数据库更新和删除

删除后

Firebase:实时数据库更新和删除

赞(0)
未经允许不得转载:srcmini » Firebase:实时数据库更新和删除

评论 抢沙发

评论前必须登录!