ı try a create user on firebase with kotlin. but i get the error toast all the time
Theese are my imports:
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_create_user.*
here the rest of my code
class createUser : AppCompatActivity() {
private var fbsignup: FirebaseAuth = FirebaseAuth.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_user)
submitButton.setOnClickListener {
val email = userSaveText.text.toString().trim()
val password = passSaveText.text.toString().trim()
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "enter a mail ", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "enter password", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
fbsignup.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "succesfully created account", Toast.LENGTH_SHORT).show()
return#addOnCompleteListener
} else {
Toast.makeText(this, "errore!!", Toast.LENGTH_SHORT).show()
return#addOnCompleteListener
}
}}
}
What am i supposed to do?
Try to remove return #setOnClickListener and return
#addOnCompleteListener from if statements
try to initiate firebaseAuth like this:
private lateinit var fbsignup:FirebaseAuth
(before on create method)
And after on create method like this:
fbsignup=FirebaseAuth.getInstance()
Related
When I click "sign in button" I got
"W/System: Ignoring header X-Firebase-Locale because its value was null"
"D/TrafficStats: tagSocket(90) with statsTag=0xffffffff, statsUid=-1" in run tab
This is my signin page codes
package com.deniz.cywm
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import android.widget.Toast
import com.deniz.cywm.databinding.ActivityMainBinding
import com.deniz.cywm.databinding.ActivityMainKayitOlBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class MainKayitOl : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainKayitOlBinding = ActivityMainKayitOlBinding.inflate(layoutInflater)
val view = binding.root
auth = FirebaseAuth.getInstance() /
setContentView(view)
binding.girisDon.setOnClickListener(){
intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
binding.kytButon.setOnClickListener(){
var kemail = binding.email.text.toString()
var ksifre = binding.sifre.text.toString()
auth.createUserWithEmailAndPassword(kemail, ksifre)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.d("TAG", "createUserWithEmail:success")
val user = auth.currentUser
} else {
Log.w("TAG", "createUserWithEmail:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}
}
}
}
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?
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()
}
I'm trying to figure out how to add more users in a Login app made with Kotlin, there's no database or whatever, the accounts are hardcoded into the program, I heard about using arrays but I'm not too sure on how to implement it in this context.
Thank you to anyone who reads this.
package com.example.textandviewbinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.example.textandviewbinding.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import java.util.*
import kotlin.system.exitProcess
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.btnSubmit.setOnClickListener {
validateUser(it)
}
}
private fun addTextView(text:String){
val textView1 = TextView(this)
textView1.text = text
textView1.textSize = 16f
textView1.textAlignment = View.TEXT_ALIGNMENT_CENTER
binding.myLayout.addView(textView1)
}
private fun validateUser(it: View) {
val username = binding.editUsername.text
val password = binding.editPassword.text
if (username.toString().equals("joed", ignoreCase = true) && password.toString().equals("1234")) {
// Toast.makeText(this, "Logged In!", Toast.LENGTH_SHORT).show()
val message = getString(R.string.welcome_message,username)
Snackbar.make(it, message, Snackbar.LENGTH_LONG)
.setAction("Show details.. ", { addTextView("Login Successful: ${Calendar.getInstance().time}" ) })
.show()
} else {
Toast.makeText(this, "Invalid Details", Toast.LENGTH_SHORT).show()
exitProcess(-1)
}
}
private fun displayToast() {
Toast.makeText(this, "Login Successful ${Calendar.getInstance().time}", Toast.LENGTH_SHORT).show()
}
}
1- Create a class called User , ex:
data class User(
var id : Int
var name : String
)
2- Create an Array of users using the User model in your MainActivity :
private val users = ArrayList<User>()
3- Add users to the array :
users.add(User(1,"Alex"))
users.add(User(2,"Andrei"))
I have my login activity working, but I can't seem to update the user's password after logging in. When I do so, it gives the password failed toast. I think the issue might be that the currentUser variable has not been defined in this script, but I'm not sure since I am fairly new to Android dev.
package com.example.testapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.FirebaseAuth
class UpdatePassword : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var passwordEt: EditText
private lateinit var changePasswordBtn: Button
private lateinit var back: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_update_password)
auth = FirebaseAuth.getInstance()
passwordEt = findViewById(R.id.password_edt_text)
changePasswordBtn = findViewById(R.id.reset_pass_btn)
back = findViewById(R.id.back_btn)
back.setOnClickListener{
finish()
}
changePasswordBtn.setOnClickListener{
var password: String = passwordEt.text.toString()
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password", Toast.LENGTH_LONG).show()
} else {
auth.currentUser?.updatePassword(password)
?.addOnCompleteListener(this, OnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Password changes successfully", Toast.LENGTH_LONG)
.show()
finish()
} else {
Toast.makeText(this, "password not changed", Toast.LENGTH_LONG)
.show()
}
})
}
}
}
}
When a task fails, there's an exception that you can inspect to find out the cause of the failure. I recommend logging it:
auth.currentUser?.updatePassword(password)
?.addOnCompleteListener(this, OnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Password changes successfully", Toast.LENGTH_LONG).show()
finish()
} else {
Log.e("updatePassword", "error", task.exception)
Toast.makeText(this, "password not changed", Toast.LENGTH_LONG).show()
}
})