【问题标题】:Unable to add data to Firebase Realtime Database from the app无法从应用程序向 Firebase 实时数据库添加数据
【发布时间】:2021-09-14 16:00:25
【问题描述】:

我尝试练习使用 Firebase 身份验证、实时数据库和存储的教程,在这个练习中我已经走了很长一段路,直到这个问题,我成功地将电子邮件和密码存储在身份验证中,它显示在 firebase 控制台上,但是问题出在数据库上,它应该在上面存储以下 HashMap,但在 firebase Realtime 控制台上没有显示任何内容

规则

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

登录类

class LoginFragment : Fragment(R.layout.fragment_login) {

    private var _binding: FragmentLoginBinding? = null
    private var firebaseUser: FirebaseUser? = null
    private lateinit var mAuth: FirebaseAuth

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mAuth = FirebaseAuth.getInstance()
        firebaseUser = FirebaseAuth.getInstance().currentUser

        if(firebaseUser != null){
            val action = LoginFragmentDirections.actionLoginFragmentToMainFragment()
            findNavController().navigate(action)
        }

        binding.apply {
            btnlogin.setOnClickListener {
                loginUser()
            }

            textViewSignUp.setOnClickListener {
                val action = LoginFragmentDirections.actionLoginFragment2ToRegisterFragment2()
                findNavController().navigate(action)
            }
        }




    }

    private fun loginUser() {
        val email: String = binding.inputEmail.text.toString()
        val password: String = binding.inputPassword.text.toString()

        if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)
        ) {
            binding.apply {
                inputEmail.error = "Email cannot be empty"
                inputPassword.error = "Password cannot be empty"
            }

        }else {
            mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener{ task->

                if(task.isSuccessful){
                    val action = LoginFragmentDirections.actionLoginFragmentToMainFragment()
                    findNavController().navigate(action)

                }else {
                    Toast.makeText(requireContext(), "Error ${task.exception?.message.toString()}", Toast.LENGTH_SHORT).show()
                }

            }
        }
    }

}

注册类

class RegisterFragment : Fragment(R.layout.fragment_register) {
    private var _binding: FragmentRegisterBinding? = null
    private lateinit var mAuth: FirebaseAuth
    private lateinit var refUsers: DatabaseReference

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentRegisterBinding.inflate(inflater, container, false)


        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mAuth = FirebaseAuth.getInstance()

        binding.apply {
            btnRegister.setOnClickListener {
                registerUser()
            }

            alreadyHaveAccount.setOnClickListener {
                findNavController().navigate(RegisterFragmentDirections.actionRegisterFragment2ToLoginFragment2())
            }


        }


    }

    private fun registerUser() {
        val userName: String = binding.inputUsername.text.toString()
        val email: String = binding.inputEmail.text.toString()
        val password: String = binding.inputPassword.text.toString()
        val confirmedPassword: String = binding.inputConformPassword.text.toString()

        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(email)
            || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmedPassword)
        ) {
            binding.apply {
                inputUsername.error = "Username cannot be empty"
                inputEmail.error = "Email cannot be empty"
                inputPassword.error = "Password cannot be empty"
                inputConformPassword.error = "Confirmed password cannot be empty"
            }
        } else if (!password.equals(confirmedPassword, ignoreCase = false)) {
            Snackbar.make(
                requireView(),
                "The Password and confirmation do not match", Snackbar.LENGTH_LONG
            ).show()
        } else {
            mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {

                        val action =
                            RegisterFragmentDirections.actionRegisterFragmentToMainFragment()

                        val firebaseUserID = mAuth.currentUser!!.uid



                        refUsers = FirebaseDatabase.getInstance().reference
                            .child(firebaseUserID)


                        val userHashMap = HashMap<String, Any>()
                        userHashMap["uid"] = firebaseUserID
                        userHashMap["username"] = userName
                        userHashMap["profile"] =
                            "https://firebasestorage.googleapis.com/v0/b/mig33-94625.appspot.com/o/icons8-test-account-100.png?alt=media&token=ce231b05-d4a7-49cb-8003-027e0d5c76e1"
                        userHashMap["cover"] =
                            "https://firebasestorage.googleapis.com/v0/b/mig33-94625.appspot.com/o/cover.jpg?alt=media&token=6bbcf0fb-77d1-4870-b714-aa13eedff86c"
                        userHashMap["status"] = "offline"
                        userHashMap["search"] = userName.lowercase()
                        userHashMap["facebook"] = "https://m.facebook.com"
                        userHashMap["instagram"] = "https://m.instagram.com"
                        userHashMap["website"] = "https://www.google.com"

                        refUsers.updateChildren(userHashMap).addOnCompleteListener { task ->
                            if (task.isSuccessful) {

                                Log.d("mido",refUsers.get().result.toString())
                                findNavController().navigate(action)
                            }
                        }

//
                    } else {
                        Toast.makeText(
                            requireContext(),
                            "Error ${task.exception?.message.toString()}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
        }

    }

}

build.gradle 依赖项

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:1.5.20"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
    implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

    implementation platform('com.google.firebase:firebase-bom:28.2.0')
    implementation 'com.google.firebase:firebase-analytics-ktx'

    implementation 'com.google.firebase:firebase-core:19.0.0'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-storage-ktx:20.0.0'
    implementation 'com.google.firebase:firebase-messaging:22.0.0'

    implementation platform('com.google.firebase:firebase-bom:28.2.0')

    // Declare the dependency for the Realtime Database library
    // When using the BoM, you don't specify versions in Firebase library dependencies
    implementation 'com.google.firebase:firebase-database-ktx'

    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.rengwuxian.materialedittext:library:2.1.4'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    implementation 'com.intuit.ssp:ssp-android:1.0.6'
    implementation 'com.intuit.sdp:sdp-android:1.0.6'

    implementation 'com.android.support:multidex:1.0.3'

}

【问题讨论】:

  • 这里的代码太多了。减少问题集,答案可能很明显:首先尝试直接写入数据库,仅此而已;没有变量,没有身份验证事件,只需先写。如果成功,请尝试将其重新添加到 createUser*() 调用中。然后尝试重新添加变量。首先隔离问题。

标签: android firebase kotlin firebase-realtime-database firebase-authentication


【解决方案1】:

我的第一个猜测是您可能在控制台中创建实时数据库之前已经下载了google-services.json 文件,这意味着该文件不包含正确的配置字符串。

如果是这种情况,您需要:

  • 下载更新的配置文件并将其添加到您的 Android 应用中,
  • 或者您可以在此处的代码中指定数据库的 URL:FirebaseDatabase.getInstance("URL to database here").reference

如果这确实是问题的原因,我们正在努力更明确地解决此配置问题(它目前隐藏在 SDK 的调试级别日志消息中,默认情况下不记录)。

【讨论】:

  • 是的,这是我在创建数据库之前下载了这个文件的问题,在更新文件之后它也不起作用,直到我像你所说的那样指定 URL https://mig33-94625-default-rtdb.europe-west1.firebasedatabase.app/
  • 感谢您确认@DrMido ?。我们正在努力更好地显示错误消息(它现在只在您enable debug logging 时记录,这不是很有用。奇怪的是重新下载后它仍然无法正常工作,所以我们会继续寻找是否可以重现那也是。
猜你喜欢
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 2018-01-12
  • 2020-02-27
  • 2021-10-04
相关资源
最近更新 更多