Инициализация базы данных Firebase не работает - PullRequest
0 голосов
/ 23 февраля 2020

Я создаю действия по регистрации пользователей. Я написал функцию для создания пользователя и сохранения его / ее информации в базе данных Firebase в реальном времени.

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

Вот код:

private var etfirstname: EditText? = null
private var etlastname: EditText? = null
private var etDateNaissance: EditText? = null
private var etemail: EditText? = null
private var etpassword: EditText? = null
private var btnCreateAccount: Button? = null
private var mProgressBar: ProgressDialog? = null

//Firebase References
private lateinit var mDatabase: FirebaseDatabase
private lateinit var mDatabaseReference: DatabaseReference


private val TAG = "CreateAccountActivity"

//Global variables
private var firstName: String? = null
private var lastName: String? = null
private var email: String? = null
private var password: String? = null
private var dateNaissance: String? = null


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

    //Initialise the references of Firebase database
    initialise()
}

//Function who initialise this references
private fun initialise() {
    etfirstname = findViewById<View>(R.id.signUp_prenom) as EditText
    etlastname = findViewById<View>(R.id.signUp_nom) as EditText
    etDateNaissance = findViewById<View>(R.id.signUp_dateNaissance) as EditText
    etemail = findViewById<View>(R.id.signUp_email) as EditText
    etpassword = findViewById<View>(R.id.SignUp_password) as EditText
    mProgressBar = ProgressDialog(this)

    btnCreateAccount?.setOnClickListener {
        createAccount()
    }
}

private fun createAccount() {

    mDatabase = FirebaseDatabase.getInstance()
    mDatabaseReference = FirebaseDatabase.getInstance().reference

    //We get current string values present in EditText gaps
    firstName = etfirstname?.text.toString()
    lastName = etlastname?.text.toString()
    dateNaissance = etDateNaissance?.text.toString()
    email = etemail?.text.toString()
    password = etpassword?.text.toString()

    //if there is text in the gaps
    if (!TextUtils.isEmpty(firstName) && !TextUtils.isEmpty(lastName)
        && !TextUtils.isEmpty(dateNaissance) && !TextUtils.isEmpty(email)
        && !TextUtils.isEmpty(password)
    ) {

        //We create a new user
        val mAuth = FirebaseAuth.getInstance()
        mAuth
            .createUserWithEmailAndPassword(email!!, password!!)
            .addOnCompleteListener(this) { task ->

                if (task.isSuccessful) {
                    //Sign in success, Update Ui with the signed-in user's information
                    Log.d(TAG, "User creation successful")
                    val userId: String = mAuth!!.currentUser!!.uid

                    verifyEmail()

                    //Update user profile information
                    val currentUserDb: DatabaseReference = mDatabaseReference!!.child(userId)
                    currentUserDb.child("FirstName").setValue(firstName)
                    currentUserDb.child("LastName").setValue(lastName)
                    currentUserDb.child("Birthday").setValue(dateNaissance)
                    currentUserDb.child("Email").setValue(email)
                    currentUserDb.child("Password").setValue(firstName)

                    updateUserInfoAndUI()
                } else {
                    //If sign in fail, display a message to the user
                    Log.w(TAG, "User creation failed", task.exception)
                    Toast.makeText(this, "Athentication failed", Toast.LENGTH_SHORT).show()
                }
            }

        //We show the progress bar while the registraton is done
        mProgressBar!!.setMessage("Enregistrement...")
        mProgressBar!!.show()

    } else {
        Toast.makeText(this, "Veuillez Entrer tout les détails", Toast.LENGTH_SHORT).show()
    }
}

//We just start a new activity here
private fun updateUserInfoAndUI() {
    val intent = Intent(this, Home_Activity::class.java)
    //The FLAG_ACTIVITY_CLEAR_TOP clear the precedent activity so that if
    // user press back from the next activity, he should not be taken back
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    startActivity(intent)
}

//Verification of the email
private fun verifyEmail() {
    val mAuth = FirebaseAuth.getInstance()
    val mUser = mAuth!!.currentUser

    mUser!!.sendEmailVerification()
        .addOnCompleteListener(this) { task ->

            if (task.isSuccessful) {
                Toast.makeText(
                    this,
                    "Verification Email sent to " + mUser.email,
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                Log.e(TAG, "sendEmailVerification", task.exception)
                Toast.makeText(this, "Failed to send verification", Toast.LENGTH_SHORT).show()
            }
        }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...