You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Realtime Database写入无响应且无报错问题求助

问题

尝试集成Firebase Realtime Database时功能异常,代码中已声明databaseReference变量,在onCreate中调用buyer()函数。点击按钮后,成功将用户数据写入Firestore并弹出“Buyer Account Created”提示,但后续写入Realtime Database的操作无响应:既不弹出“Added to realtime database”提示,也不执行页面跳转逻辑,且Logcat无任何错误信息。

相关代码如下:

private lateinit var databaseReference: DatabaseReference
private fun buyer(){
    findViewById<EditText>(R.id.shopName).visibility = View.GONE
    findViewById<EditText>(R.id.shopStreet).visibility = View.GONE
    findViewById<EditText>(R.id.shopCity).visibility = View.GONE
    findViewById<EditText>(R.id.shopState).visibility = View.GONE
    findViewById<EditText>(R.id.pinCode).visibility = View.GONE
    findViewById<EditText>(R.id.shopGstIn).visibility = View.GONE
    val letsGoButton = findViewById<Button>(R.id.letsGo)
    val layoutParams = letsGoButton.layoutParams as ConstraintLayout.LayoutParams
    layoutParams.verticalBias = 0.5f
    letsGoButton.layoutParams = layoutParams
    letsGoButton.setOnClickListener {
        val sName = findViewById<EditText>(R.id.name).text.toString()
        val sContactNo = findViewById<EditText>(R.id.contactNo).text.toString()
        val sUserName = findViewById<EditText>(R.id.username).text.toString()
        val sType = "buyer"
        if (sName.isNotEmpty() && sContactNo.isNotEmpty() && sUserName.isNotEmpty() && sType.isNotEmpty()) {
            val userMap = hashMapOf(
                "name" to sName,
                "contactNo" to sContactNo,
                "username" to sUserName,
                "type" to sType
            )

            val userId = FirebaseAuth.getInstance().currentUser!!.uid
            val userMap2 = hashMapOf(
                "name" to sName,
                "userId" to userId
            )

            db.collection("user").document(userId).set(userMap).addOnSuccessListener {
                Toast.makeText(this, "Buyer Account Created", Toast.LENGTH_SHORT).show()

                databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userId)
                databaseReference.setValue(userMap2).addOnSuccessListener {
                    Toast.makeText(this, "Added to realtime database", Toast.LENGTH_SHORT).show()
                    val auth = FirebaseAuth.getInstance()
                    auth.signOut()
                    startActivity(Intent(this, WelcomeScreenActivity::class.java))
                    finish()
                }.addOnFailureListener {
                    Toast.makeText(this, it.localizedMessage, Toast.LENGTH_SHORT).show();
                }
            }.addOnFailureListener {
                Toast.makeText(this, "Please try again", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "Fill all the details", Toast.LENGTH_SHORT).show()
        }
    }
}
可能的原因及解决方案
  • Realtime Database权限配置错误
    默认安全规则仅允许已认证用户读写,但可能规则条件不满足或未正确开放写入权限。进入Firebase控制台的Realtime Database规则页面,确认当前认证用户拥有Users节点的写入权限。开发环境可临时使用宽松测试规则(正式环境需替换为严格规则):

    {
      "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
      }
    }
    
  • Realtime Database实例未指定正确URL
    若存在多个数据库实例,未指定URL会导致初始化错误。尝试显式传入数据库URL:

    databaseReference = FirebaseDatabase.getInstance("你的Realtime Database完整URL").getReference("Users").child(userId)
    

    URL可在Firebase控制台的Realtime Database页面获取。

  • 异步回调未在主线程执行
    Realtime Database的回调可能在子线程运行,导致Toast无法显示、页面跳转逻辑不执行。将回调内的UI操作切换到主线程:

    databaseReference.setValue(userMap2).addOnSuccessListener {
        runOnUiThread {
            Toast.makeText(this, "Added to realtime database", Toast.LENGTH_SHORT).show()
            FirebaseAuth.getInstance().signOut()
            startActivity(Intent(this, WelcomeScreenActivity::class.java))
            finish()
        }
    }.addOnFailureListener {
        runOnUiThread {
            Toast.makeText(this, it.localizedMessage, Toast.LENGTH_SHORT).show()
        }
    }
    
  • 变量初始化时机问题
    代码中在Firestore回调内初始化databaseReference,若Firebase核心初始化不完整,可能导致实例异常。将初始化提前到onCreate中:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.your_activity_layout)
        databaseReference = FirebaseDatabase.getInstance().getReference("Users")
        buyer()
    }
    

    后续回调中直接使用:

    databaseReference.child(userId).setValue(userMap2)...
    
  • Logcat过滤隐藏了错误信息
    取消Logcat的过滤条件,直接搜索Firebase或Database关键词,查看是否有未显示的警告或错误日志。


内容的提问来源于stack exchange,提问作者Ajay Satpati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 04:37:08