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]
}
}
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
Related
I am having some issues with Firebase auth. I'm building an app using using Kotlin but keep retrieving the error 'W/System: Ignoring header X-Firebase-Locale because its value was null.'
I had this working previously, when I had set up the application using activities. I've now moved towards MVP architecture, but this seems to have broken my firebase authentication. I have also ensured that Email/Password sign in method has been enabled in the Firebase console.
If anyone could please take a look and hopefully you can see where I am going wrong. Many thanks.
SignInView
package org.wit.hikingtrails.views.signIn
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.wit.hikingtrails.databinding.ActivitySignInBinding
import com.google.firebase.auth.FirebaseAuth
import org.wit.hikingtrails.activities.SignUpActivity
import org.wit.hikingtrails.views.hikeList.HikeListView
import org.wit.hikingtrails.views.signUp.SignUpView
class SignInView : AppCompatActivity() {
lateinit var presenter: SignInPresenter
private lateinit var binding: ActivitySignInBinding
private lateinit var firebaseAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
presenter = SignInPresenter( this)
super.onCreate(savedInstanceState)
binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
binding.textView.setOnClickListener {
val intent = Intent(this, SignUpView::class.java)
startActivity(intent)
}
binding.button.setOnClickListener {
val email = binding.emailEt.text.toString()
val pass = binding.passET.text.toString()
if (email.isNotEmpty() && pass.isNotEmpty()) {
presenter.doLogin(email, pass)
} else {
Toast.makeText(this, "Empty Fields Are not Allowed !!", Toast.LENGTH_SHORT).show()
}
}
}
override fun onStart() {
super.onStart()
if(firebaseAuth.currentUser != null){
val intent = Intent(this, HikeListView::class.java)
startActivity(intent)
}
}
}
SignInPresenter:
package org.wit.hikingtrails.views.signIn
import android.content.ContentValues.TAG
import android.content.Intent
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.google.firebase.auth.FirebaseAuth
import org.wit.hikingtrails.views.hikeList.HikeListView
import timber.log.Timber
import timber.log.Timber.i
class SignInPresenter (val view: SignInView) {
private lateinit var loginIntentLauncher : ActivityResultLauncher<Intent>
init{
registerLoginCallback()
}
var auth: FirebaseAuth = FirebaseAuth.getInstance()
fun doLogin(email: String, pass: String) {
// view.showProgress()
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(view) { task ->
if (task.isSuccessful) {
val launcherIntent = Intent(view, HikeListView::class.java)
loginIntentLauncher.launch(launcherIntent)
} else {
i("Login failed:")
// val launcherIntent = Intent(view, HikeListView::class.java)
// loginIntentLauncher.launch(launcherIntent)
}
// view.hideProgress()
}
}
private fun registerLoginCallback(){
loginIntentLauncher =
view.registerForActivityResult(ActivityResultContracts.StartActivityForResult())
{ }
}
}
For anyone that was having the same issue: The issue was with my API key. In kotlin, to debug, I used Timber.i( "signInWithCredential:failure ${task.exception?.message}") within the else statement of doLogin() in the presenter
I am new to Android. I create sign-in and sign-up functionality. But I want to store the data of the user,(before going to the signing screen) when the user is signing up in the FireBase FireStore (based on the current user id). I have the user id, but I don't know the way to do it. The code is attached below. I am glad, If someone could help.
package com.example.firebase
import android.content.Intent
import android.os.Binder
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.firebase.databinding.ActivitySignUpBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
class Sign_Up_Activity : AppCompatActivity() {
private lateinit var binding: ActivitySignUpBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var firebasefirestore: FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
firebasefirestore = FirebaseFirestore.getInstance()
binding.signUpButton.setOnClickListener {
val email = binding.emailEt.text.toString()
val password = binding.passET.text.toString()
val confirmPass = binding.confirmPassEt.text.toString()
if (email.isNotEmpty() && password.isNotEmpty() && confirmPass.isNotEmpty()) {
if (password.equals(confirmPass)) {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
val userid:String= firebaseAuth.currentUser!!.uid
firebasefirestore.collection("user").document(userid).get()
Log.d("User id",userid)
val intent = Intent(this, Sign_In_Activity::class.java)
startActivity(intent)
} else {
Toast.makeText(this, it.exception.toString(),
Toast.LENGTH_SHORT)
.show()
}
}
} else {
Toast.makeText(this, "Password is not matching",
Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Empty Fields are not Allowed",
Toast.LENGTH_SHORT).show()
}
}
}
}
When you're using the following line of code:
firebasefirestore.collection("user").document(userid).get()
You aren't setting the user to Firestore, you're only reading it. If you want to add the data to the database, you have to use set() like in the following lines of code:
val db = Firebase.firestore
val user = mapOf("email" to firebaseAuth.currentUser!!.email)
val userRef = db.collection("user")
userRef.document(userid).set(user)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
If you're interested in implementing Firebase authentication with Google, then please check the following article:
How to authenticate to Firebase using Google One Tap in Jetpack Compose?
If you want by chance to implement the anonymous authentication, then please check:
How to handle Firebase Authentication in clean architecture using Jetpack Compose?
This question already has answers here:
Firebase Realtime Database connection killed: Different Region
(5 answers)
Closed 9 months ago.
I am making a Tinderr clone and i want to store the users in the realtime database of Firebase. I have followed the documentation and multiple youtube vids but nothing works. The users do get stored in the authentication so why not in the database?
SignupActivity :
package com.example.dogsharev2.activities
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.example.dogsharev2.R
import com.example.dogsharev2.util.DATA_USERS
import com.example.dogsharev2.util.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_signup.*
class SignupActivity : AppCompatActivity() {
private val firebaseDatabase = FirebaseDatabase.getInstance().reference
private val firebaseAuth = FirebaseAuth.getInstance()
private val firebaseAuthListener = FirebaseAuth.AuthStateListener {
val user = firebaseAuth.currentUser
if(user != null) {
startActivity(MainActivity.newIntent(this))
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signup)
}
override fun onStart() {
super.onStart()
firebaseAuth.addAuthStateListener(firebaseAuthListener)
}
override fun onStop() {
super.onStop()
firebaseAuth.removeAuthStateListener(firebaseAuthListener)
}
fun onSignup(v: View) {
if(!emailET.text.toString().isNullOrEmpty() && !passwordET.text.toString().isNullOrEmpty()) {
firebaseAuth.createUserWithEmailAndPassword(emailET.text.toString(), passwordET.text.toString())
.addOnCompleteListener { task ->
if(!task.isSuccessful) {
Toast.makeText(this, "Signup error ${task.exception?.localizedMessage}", Toast.LENGTH_SHORT).show()
} else {
val email = emailET.text.toString()
val userId = firebaseAuth.currentUser?.uid ?: ""
val user = User(userId, "", "", email, "", "", "")
firebaseDatabase.child(DATA_USERS).child(userId).setValue(user)
}
}
}
}
companion object {
fun newIntent(context: Context?) = Intent(context, SignupActivity::class.java)
}
}
Data.kt
package com.example.dogsharev2.util
data class User(
val uid: String? = "",
val name: String? = "",
val age: String? = "",
val email: String? = "",
val gender: String? = "",
val preferredGender: String? = "",
val imageUrl: String? = ""
)
Constabts.kt
ackage com.example.dogsharev2.util
val DATA_USERS = "Users"
I have implemented 'com.google.firebase:firebase-database-ktx:20.0.5' also. And set the rules of my database to true.
Thanks in advance
I have analyzed it multiple times and everything seems perfectly fine. What you can do is to add a listener to setValue(user) method like this:
firebaseDatabase.child(DATA_USERS).child(userId).setValue(user)
.addOnCompleteListener { task ->
if(task.isSuccessful) {
Toast.makeText(this, "Successful", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
Now task.getException().getMessage() will let you know what the actual problem is about saving your user data.
I am building a registration activity for my app. I am using Kotlin und Firebase authentication. The registrazion itself already workds perfectly well (as well as the login acitivity).
My next goal is to save the user data (first of all the email) in the firebase database if the registration was successfull.
The function that I am using for that looks like that:
fun writeNewUser(userId: String, email: String) {
val user = User(email)
database.child("users").child(userId).setValue(user)
}
Here is the complete activity. There are no errors, my current problem is that the writeNewUser function is never used. Does anyone know why that could be?
package com.carlschwein.servus
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
class RegistrationActivity : AppCompatActivity() {
lateinit var etEmail: EditText
lateinit var etConfPass: EditText
private lateinit var etPass: EditText
private lateinit var btnSignUp: Button
lateinit var tvRedirectLogin: TextView
private lateinit var auth: FirebaseAuth
private lateinit var database: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.registration)
// View Bindings
etEmail = findViewById(R.id.etSEmailAddress)
etConfPass = findViewById(R.id.etSConfPassword)
etPass = findViewById(R.id.etSPassword)
btnSignUp = findViewById(R.id.btnSSigned)
tvRedirectLogin = findViewById(R.id.tvRedirectLogin)
database = Firebase.database.reference
// Initialising auth object
auth = Firebase.auth
btnSignUp.setOnClickListener {
signUpUser()
}
// switching from signUp Acitity to Login Activity
tvRedirectLogin.setOnClickListener {
startActivity(Intent(this, LoginActivity::class.java))
}
}
private fun signUpUser() {
val email = etEmail.text.toString()
val pass = etPass.text.toString()
val confirmPassword = etConfPass.text.toString()
// check pass
if (email.isBlank() || pass.isBlank() || confirmPassword.isBlank()) {
Toast.makeText(this, "Email und/oder Passwort dürfen nicht leer sein.", Toast.LENGTH_SHORT).show()
return
}
if (pass != confirmPassword) {
Toast.makeText(this, "Die beiden Passwörter stimmen nicht überein.", Toast.LENGTH_SHORT)
.show()
return
}
// If all credential are correct
// We call createUserWithEmailAndPassword
// using auth object and pass the
// email and pass in it.
auth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this) {
if (it.isSuccessful) {
Toast.makeText(this, "Registrierung erfolgreich!", Toast.LENGTH_SHORT).show()
fun writeNewUser(userId: String, email: String) {
val user = User(email)
database.child("users").child(userId).setValue(user)
}
startActivity(Intent(this,LoginActivity::class.java))
finish()
} else {
Toast.makeText(this, "Registrierung fehlgeschlagen. Daten bereits vorhanden oder fehlerhaft.", Toast.LENGTH_SHORT).show()
}
}
}
}
fun writeNewUser(userId: String, email: String) is not being called, you can move the function declaration outside of the completion listener attached to createUserWithEmailAndPassword then call the function inside.
Like:
if (it.isSuccessful) {
Toast.makeText(this, "Registrierung erfolgreich!", Toast.LENGTH_SHORT).show()
>>>>>> HERE
val uid = auth.currentUser.uid
writeNewUser(uid, email)
startActivity(Intent(this,LoginActivity::class.java))
finish()
} else {
Toast.makeText(this, "Registrierung fehlgeschlagen. Daten bereits vorhanden oder fehlerhaft.", Toast.LENGTH_SHORT).show()
}
This question already has answers here:
Firebase code not creating new user
(8 answers)
Closed last year.
I am trying to add a new user to my real-time database but getting "Failed Login" every time. I don't know where's the problem. "Loginfirebase" is my function for adding new users to the database, if a user is added successfully then I am calling "loadmain" function from where I am changing to other activity.
package com.example.tictactoe
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_room.*
class RoomActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_room)
login.setOnClickListener {
buLoginEvent()
}
}
fun buLoginEvent(){
val emailString = email.text.toString()
val passwordString = password.text.toString()
if(emailString.isNotEmpty() && passwordString.isNotEmpty()) {
LoginToFirebase(emailString, passwordString);
} else {
//show error message to user
Toast.makeText(this, "Email or Password cannot be empty!!", Toast.LENGTH_LONG).show()
}
}
fun LoginToFirebase(email:String, password:String){
var mAuth: FirebaseAuth = FirebaseAuth.getInstance()
var database = FirebaseDatabase.getInstance()
var myRef = database?.reference
var currentUser = mAuth!!.currentUser
mAuth!!.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this){
task->
if(task.isSuccessful){
Toast.makeText(applicationContext,"Successful Login", Toast.LENGTH_LONG).show()
//saving in database
myRef.child("Users").child(splitString(currentUser!!.email.toString())).setValue(
currentUser!!.uid
)//creating current node iin realtime database
LoadMain()
}
else{
Toast.makeText(applicationContext,"Failed Login", Toast.LENGTH_LONG).show()
}
}
}
override fun onStart() {//2nd time when the application is started then call this method
super.onStart()
LoadMain()
}
fun LoadMain(){
var mAuth: FirebaseAuth = FirebaseAuth.getInstance()
var currentUser = mAuth!!.currentUser
if(currentUser!=null) {// doing this only when the user is not null
var intent = Intent(this, OnlineGameActivity::class.java)
intent.putExtra("email", currentUser!!.email)
intent.putExtra("uid", currentUser!!.uid)
startActivity(intent)
finish()
}
else{
}
}
fun splitString(str:String):String{
var split=str.split("#")
return split[0]
}
}
If a Task fails it contains an exception that tells you the cause of the failure, so you might want to write that to the logcat to find the root cause of your problem with:
mAuth!!.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this){
task->
if(task.isSuccessful){
Toast.makeText(applicationContext,"Successful Login", Toast.LENGTH_LONG).show()
//saving in database
myRef.child("Users").child(splitString(currentUser!!.email.toString())).setValue(
currentUser!!.uid
)//creating current node iin realtime database
LoadMain()
}
else{
Toast.makeText(applicationContext,"Failed Login", Toast.LENGTH_LONG).show()
Log.e("FirebaseAuth", "Failed login", task.getException()); // 👈
}
}