在 Firebase 实时数据库中保存数据 Android Studio Kotlin

Posted

技术标签:

【中文标题】在 Firebase 实时数据库中保存数据 Android Studio Kotlin【英文标题】:Save Data in Firebase Realtime Database Android Studio Kotlin 【发布时间】:2021-12-30 06:32:02 【问题描述】:

如何使用 Kotlin 语言将我的用户注册表单的所有数据字段保存在 android Studio 上的 Firebase 实时数据库中?

目前我的应用程序正在成功注册帐户,但我还希望将 cnic、号码、车牌号和用户姓名等自定义字段存储在 firebase 实时数据库中。工作代码如下。

class SignUpActivity : AppCompatActivity() 

    //view binding
    private lateinit var binding: ActivitySignUpBinding

    //action bar
    private lateinit var actionBar: ActionBar

    //progression bar
    private lateinit var progressDialog: ProgressDialog

    //firebase auth
    private lateinit var firebaseAuth: FirebaseAuth
    private var name = ""
    private var email = ""
    private var password = ""
    private var platenumber = ""
    private var number = ""
    private var cnic = ""

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        binding = ActivitySignUpBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //config actionbar enable back button
        actionBar = supportActionBar!!
        actionBar.title = "Sign Up"
        actionBar.setDisplayHomeAsUpEnabled(true)
        actionBar.setDisplayShowHomeEnabled(true)

        //config progress dialog
        progressDialog = ProgressDialog(this)
        progressDialog.setTitle("Wait Please")
        progressDialog.setMessage("Creating account...")
        progressDialog.setCanceledOnTouchOutside(false)

        //init firebaseauth
        firebaseAuth = FirebaseAuth.getInstance()

        //handle click begin signup
        binding.signupButton.setOnClickListener 
            //validate data
            validateData()
        


    

    private fun validateData() 
        //get data
        name = binding.nameET.text.toString().trim()
        email = binding.emailET.text.toString().trim()
        password = binding.passwordET.text.toString().trim()
        platenumber = binding.dobET.text.toString().trim()
        number = binding.numberET.text.toString().trim()
        cnic = binding.cnicET.text.toString().trim()

        //validate data
         if (TextUtils.isEmpty(name))
            //no password entered
            binding.nameET.error = "Enter Name"
        
        else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
            //invalid email
            binding.emailET.error = "Invalid Email"
        
        else if (TextUtils.isEmpty(password))
            // no password entered
            binding.passwordET.error = "Enter Password"
        

        else if (TextUtils.isEmpty(platenumber))
        // no password entered
            binding.dobET.error = "Enter Vehicle Plate Number"
        
        else if (TextUtils.isEmpty(number))
        // no password entered
            binding.numberET.error = "Enter Contact Number"
        
        else if (TextUtils.isEmpty(cnic))
        // no password entered
            binding.cnicET.error = "Enter CNIC Number"
        
        else if (password.length<6)
            binding.passwordET.error = "Enter a Password of Atleast 6 Characters"
        
        else if (number.length<11)
            binding.passwordET.error = "Enter full 11 Digit Number"
        
        else if (cnic.length<13)
            binding.passwordET.error = "Enter full 13 Digit CNIC Number"
        
        else
        //data is valid signup new user
        firebaseSignUp()
        
    

    private fun firebaseSignUp() 
        progressDialog.show()
        //create account
        firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this) 
                //signup success
                progressDialog.dismiss()
                //get current user
                val firebaseUser = firebaseAuth.currentUser
                val email = firebaseUser!!.email
                Toast.makeText(this, "Account  Created With Email $email",Toast.LENGTH_SHORT).show()
                //start activity
                startActivity(Intent(this, ProfileActivity::class.java))
                finish()

            
            .addOnFailureListener e->
                //signup fial
                progressDialog.dismiss()
                Toast.makeText(this, "Signup failed due to $e.message",Toast.LENGTH_SHORT).show()
            

    

    override fun onSupportNavigateUp(): Boolean 
        onBackPressed() // go back to previous activity
        return super.onSupportNavigateUp()
    

【问题讨论】:

【参考方案1】:

如果您想为每个用户存储这些值,您可以执行以下操作:

private fun firebaseSignUp() 
    progressDialog.show()
    //create account
    firebaseAuth.createUserWithEmailAndPassword(email, password)
        .addOnSuccessListener(this)  // ? Change to success listener
            //signup success
            progressDialog.dismiss()
            //get current user
            val firebaseUser = firebaseAuth.currentUser
            val email = firebaseUser!!.email

            // ? create a map of value
            val profile = mapOf(
                cnic to "cnic",
                number to "number",
                platenumber to "platenumber",
                name to "name"
            )
            // ? write to database
            vak database = Firebase.database.reference
            database.child("users").child(firebaseUser!!.uid).setValue(profile)

            Toast.makeText(this, "Account  Created With Email $email",Toast.LENGTH_SHORT).show()
            //start activity
            startActivity(Intent(this, ProfileActivity::class.java))
            finish()
        
        .addOnFailureListener e->
            //signup fial
            progressDialog.dismiss()
            Toast.makeText(this, "Signup failed due to $e.message",Toast.LENGTH_SHORT).show()
        

我建议您还阅读 reading from and writing to the database 上的 Firebase 文档。

【讨论】:

以上是关于在 Firebase 实时数据库中保存数据 Android Studio Kotlin的主要内容,如果未能解决你的问题,请参考以下文章

在 Flutter 中将数据保存到 Firebase 实时数据库

如何在实时 Firebase 数据库中保存上传图片的完美 url-link?

如何在Firebase实时数据库中保存LocalData?

Firebase 实时数据库不保存注册页面中的数据

向 Firebase 实时数据库添加新值时如何保存当前日期/时间

如何保存多个谷歌地图标记,它们在 Firebase 实时数据库中的位置,并在打开应用程序时再次显示它们