Sahil
Sahil

Reputation: 75

Firebase Database not storing data, logcat shows no error

I am learning Kotlin and trying to save email and UID of users in firebase database when they login in the app but the data doesn't get stored in the database and the logcat shows no error so I can't figure out what's the problem.

P.S. - I have set firebase database rules to

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

here's the login.kt file code

package com.revorg.tictactoe

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_login.*

class Login : AppCompatActivity() {

var mFirebaseAuth: FirebaseAuth?=null

var database = FirebaseDatabase.getInstance()
var myRef=database.reference

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

    mFirebaseAuth= FirebaseAuth.getInstance()
}

fun buLoginEvent(view:View){

    LoginToFirebase(etEmail.text.toString(),etPassword.text.toString())
}

fun LoginToFirebase(email:String,password:String){

    mFirebaseAuth!!.createUserWithEmailAndPassword(email,password)
            .addOnCompleteListener(this) {task ->

                if(task.isSuccessful){
                    Toast.makeText(applicationContext,"Login Successful",Toast.LENGTH_SHORT).show()
                    var currentuser = mFirebaseAuth!!.currentUser
                    //save to Database
                    if(currentuser!=null) {
                        myRef.child("Users").child(splitString(currentuser.email.toString())).child(currentuser.uid)
                    }

                    LoadMain()

                } else {
                    Toast.makeText(applicationContext,"Login Failed", Toast.LENGTH_SHORT).show()
                }
            }

}

override fun onStart() {
    super.onStart()

    LoadMain()
}

fun LoadMain(){

    var currentuser = mFirebaseAuth!!.currentUser

    if(currentuser!=null) {


        var intent = Intent(this, MainActivity::class.java)
        intent.putExtra("email", currentuser.email)
        intent.putExtra("uid", currentuser.uid)

        startActivity(intent)
    }
}

fun splitString(str:String):String{

    var split = str.split("@")
    return split[0]
}
}

Upvotes: 3

Views: 3193

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

Nothing is getting stored, because you are not storing anything, you need to use setValue() to store data. The child() gets reference to a location in the database.

You should do this:

myRef.child("Users").child(currentuser.uid).child("email").setValue(email);

Then you would have this database:

Users
  userUid
     email: email_here

Upvotes: 3

Related Questions