База данных в реальном времени не получает данные в firebase

# #android #firebase #kotlin #firebase-realtime-database #firebase-security

Вопрос:

Я использую базу данных в реальном времени для сохранения информации о пользователе , но проблема в том , что она вообще не работает , между тем хранилище и облачный магазин firestore работают должным образом , пробовал изменять правила, пробовал разные методы, но ни один из них не сработал, если кто-то может помочь, заранее благодарю вас .

  • Это мой код
 
class CustomerRegistrationActivity : AppCompatActivity() {
    private lateinit var imageDownloadUrl : String
    private var imageUrl : Uri? = null
    private lateinit var firebaseAuth: FirebaseAuth
    private lateinit var databaseReference: DatabaseReference
    private lateinit var storageReference: StorageReference
    private var _binding : ActivityCustomerRegistrationBinding?  = null
    private val binding get() = _binding!!
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityCustomerRegistrationBinding.inflate(layoutInflater)
        setContentView(binding.root)


        init()

        binding.register.setOnClickListener {
            binding.register.startAnimation()
            registerNewCustomer()
        }

        binding.customerImg.setOnClickListener {
            selectCustomerImage()
        }

        binding.haveAccount.setOnClickListener {
            Intent(this, CustomerLoginAcitivity::class.java).apply {
                startActivity(this)
                finish()
            }
        }
    }

    private fun init(){
        firebaseAuth = FirebaseAuth.getInstance()
        databaseReference = FirebaseDatabase.getInstance().reference
        storageReference = FirebaseStorage.getInstance().reference
    }
    private fun registerNewCustomer(){
        val customerUserName  = binding.userName.text.toString()
        val customerPhone = binding.phone.text.toString()
        val customerEmail  = binding.email.text.toString()
        val customerPassword = binding.password.text.toString()

        if(TextUtils.isEmpty(customerUserName)){
            Toast.makeText(this,"Missing Username..",Toast.LENGTH_SHORT).show()
            return
        }
        if(TextUtils.isEmpty(customerPhone)){
            Toast.makeText(this,"Missing phone..",Toast.LENGTH_SHORT).show()
            return
        }
        if(TextUtils.isEmpty(customerEmail)){
            Toast.makeText(this,"Missing Email..",Toast.LENGTH_SHORT).show()
            return
        }
        if(TextUtils.isEmpty(customerPassword)){
            Toast.makeText(this,"Missing password..",Toast.LENGTH_SHORT).show()
            return
        }

        lifecycleScope.launch(Dispatchers.Main) {
            try {
              // creating user account 
               firebaseAuth.createUserWithEmailAndPassword(customerEmail,customerPassword).await()

 
                // check if image url is not null
                imageDownloadUrl = if(imageUrl == null){
                    ""
                } else {
                    // if url not null , push into firestorage
                    val task = storageReference.child("Customers")
                        .child(firebaseAuth.currentUser?.uid!!).putFile(imageUrl!!)
                    task.await().storage.downloadUrl.toString()
                }

                // creating a map for user info
                val credentialsMap = hashMapOf<String,Any>()
                credentialsMap["customerName"] = customerUserName
                credentialsMap["customerEmail"] = customerEmail
                credentialsMap["CustomerPhone"] = customerPhone
                credentialsMap["accountType"] = "Customer"
                credentialsMap["profileImage"] = imageDownloadUrl


                // pushing data into realtime database
                // the issue is here , i even debugged the code , it executes but don't pass to 
                // to the next code and it is not saving data
                databaseReference
                        .child("customers")
                        .child(firebaseAuth.currentUser?.uid!!)
                        .setValue(credentialsMap).await()

                 // the code here gets never exeucte but there is issue with code above of real db
                binding.register.stopAnimation()

                CoroutineScope(Dispatchers.Main).launch {
                    delay(1000)
                    Intent(this@CustomerRegistrationActivity,CustomerMainActivity::class.java).apply {
                        startActivity(this)
                        finish()
                    }
                }

            }catch (ex : Exception){
                binding.register.stopAnimation()
                Log.d(Utils.ACTIVITY_TAG,"Exception Registration ${ex.message}")
            }
        }
    }
    private fun selectCustomerImage(){
        Intent().apply {
            type = "image/*"
            action = Intent.ACTION_GET_CONTENT
            startActivityForResult(this, IMAGE_REQUEST_CODE)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == IMAGE_REQUEST_CODE){
            data?.data.let {
                imageUrl = it
                binding.customerImg.setImageURI(imageUrl)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

    companion object {
        const val IMAGE_REQUEST_CODE = 1001
    }
}
 
  • Правила БД в реальном времени
 {
  "rules": {
       ".read": "auth !== null",
       ".write": "auth !== null"
  }
}
 

Комментарии:

1. Вероятно, вам это понадобится addOnFailureListener , когда вы установите значение firebase и зарегистрируете сообщение обратного вызова, чтобы увидеть ошибку

Ответ №1:

Попробуйте удалить .await() при нажатии и установите для правил бд значение true

 ".read": true,
".write": true
 

Комментарии:

1. Я действительно установил его в значение true , и это не сработало , сейчас это сработало , но действительно странно, я восстановил и очистил проект, он работал . не знаю почему , спасибо тебе за ответ и за твое время, приятель .

2. ".read": true и ".write": true имеют свои собственные последствия. Установка истинных разрешений на чтение и запись означает просто предоставление общедоступного доступа для чтения и изменения (даже удаления) базы данных. Пожалуйста, используйте надлежащие правила безопасности для защиты вашей базы данных от вредоносных действий. Для получения дополнительной информации о рекомендациях по правилам безопасности Firebase посетите firebase.google.com/docs/rules/insecure-rules