Firebase auth not successful - android

I've been trying so make auth with firebase and all went pretty well. But at the moment i tested it, it didn't work. The problem is that the function called createUserWithEmailAndPassowrd is not successful. I think the firebase it's connected to android studio, because the analytics works perfectly. Could you give me a hand please?
Here is the code:
package com.example.authtest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val etEmail = findViewById<EditText>(R.id.EmailEt)
val etPwd = findViewById<EditText>(R.id.PasswordEt)
val registerBtn = findViewById<Button>(R.id.RegisterBtn)
val logInBtn = findViewById<Button>(R.id.LogInBtn)
val tvMessage = findViewById<TextView>(R.id.MessageTv)
val auth = FirebaseAuth.getInstance()
registerBtn.setOnClickListener {
if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
auth.createUserWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
if (it.isSuccessful) {
tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
} else {
tvMessage.text = "Error registering your account!"
}
}
}
}
logInBtn.setOnClickListener {
if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
auth.signInWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
if (it.isSuccessful) {
tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
} else {
tvMessage.text = "Incorrect username/password!"
}
}
}
}
}
}
Thanks in advance!

Try posting the code where you have defined the function.
----OR-----
The function in my code is defined like this:
loginButton.setOnClickListener{
val emailID:String=loginEmail.text.toString().trim{it <=' '}
val pass:String=loginPassword.text.toString().trim{it <=' '}
when{
TextUtils.isEmpty(emailID)->{
Toast.makeText(this#Login,"Enter Email ID! ", LENGTH_SHORT).show()
}
TextUtils.isEmpty(pass)-> {
Toast.makeText(this#Login, "Enter Password! ", LENGTH_SHORT).show()
}
else->{
FirebaseAuth.getInstance().signInWithEmailAndPassword(emailID,pass).addOnCompleteListener{ task->
if(task.isSuccessful){
//Store user id in a variable to pass on main activity:
val firebaseUser: FirebaseUser = task.result!!.user!!
Toast.makeText(this#Login,"Logged In Successfully" ,LENGTH_SHORT).show()
val intent = Intent(this#Login,MainActivity::class.java)
intent.flags= Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
intent.putExtra("user_id",firebaseUser)
intent.putExtra("email_id",emailID)
startActivity(intent)
finish()
}else{
Toast.makeText(this#Login,task.exception!!.message.toString(),
LENGTH_SHORT).show()
}
}
}
}
}
OR checkout this repo. It has login, register functions defined, which work perfectly.

The auth.createUserWithEmailAndPassword call (and many other Firebase API calls) returns a Task that is marked as either being successful or as having failed. In the case where the task has failed, it contains an exception that gives the root cause of that failure.
You should log the exception, and fix the root cause:
FirebaseAuth.getInstance().signInWithEmailAndPassword(emailID,pass)
.addOnCompleteListener{ task->
if (task.isSuccessful) {
...
} else {
Log.e("Firebase Auth", "Sign-in failed", task.exception); // 👈
Toast.makeText(this#Login,task.exception!!.message.toString(),
LENGTH_SHORT).show()
}
}

Try below code:
createUserWithEmailAndPassword() and signInWithEmailAndPassword() methods require strings as parameter but you are providing editext in these parameters
registerBtn.setOnClickListener {
if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
auth.createUserWithEmailAndPassword(etEmail.text.toString().trim(),etPwd.text.toString().trim()).addOnCompleteListener {
if (it.isSuccessful) {
tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
} else {
tvMessage.text = "Error registering your account!"
}
}
}
}
logInBtn.setOnClickListener {
if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
auth.signInWithEmailAndPassword(etEmail.text.toString().trim(),etPwd.text.toString().trim()).addOnCompleteListener {
if (it.isSuccessful) {
tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
} else {
tvMessage.text = "Incorrect username/password!"
}
}
}
}

Related

Program wont progress after firebase user registration

This activity registers a user in firebase auth, uploads info in Realtime database and uploads user picture in Storage.
This code (I don't know why) gets stuck when it registers the user. If you see, I've added Log statements to break this entire process. The log is like
STARTING PROCESS
BEFORE
INSIDE
No other statement. I think I am using coroutines correctly but I don't know why this program doesn't go further than this ^. Should I use callbacks? Am I using coroutines in a wrong way?A lso any other suggestion will be appreciated.
class SignUpActivity : AppCompatActivity() {
private lateinit var binding: ActivitySignUpBinding
private lateinit var firebaseAuth : FirebaseAuth
private lateinit var firebaseStorage: FirebaseStorage
private lateinit var firebaseDatabase: FirebaseDatabase
val TAG ="SIGNUPATAG"
var selectedPhoto : Uri? = null
var IMAGE_RESPONE_CODE = 1;
var isOk = false;
val imageUrl : String = "."
var userUID = "."
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
binding.signupTvSelectPhoto.setOnClickListener {
val intent = Intent();
intent.type = "image/*"
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Pic"),IMAGE_RESPONE_CODE)
}
binding.signupBtnSignUp.setOnClickListener {
val email = binding.signupEtvEmail.text.toString()
if(email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.signupEtvEmail.error = "Invalid Email Address"
binding.signupEtvEmail.requestFocus()
return#setOnClickListener
}
if(binding.signupEtvName.text.length < 3) {
binding.signupEtvName.error= "Name should at least have 3 characters"
binding.signupEtvName.requestFocus()
return#setOnClickListener
}
val password = binding.signupEtvPassword.text.toString()
if(password.length < 4) {
binding.signupEtvPassword.error = "Password should at least have 4 characters."
binding.signupEtvPassword.requestFocus()
return#setOnClickListener
}
// All Okay
Log.d(TAG,"STARTING PROCESS")
binding.pbSignup.visibility = View.VISIBLE
createAccount(email,password,binding.signupEtvName.text.toString())
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 1) {
if(data != null) {
selectedPhoto = data?.data
binding.signupImgvPhoto.setImageURI(selectedPhoto)
}
else {
val context = this
selectedPhoto = Uri.parse(
ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
+ context.getResources().getResourcePackageName(R.drawable.profilepicnormall) + '/'
+ context.getResources().getResourceTypeName(R.drawable.profilepicnormall) + '/'
+ context.getResources().getResourceEntryName(R.drawable.profilepicnormall) )
}
}
}
private fun createAccount(email : String, password : String,name:String) {
val context = this
selectedPhoto = Uri.parse(
ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
+ context.getResources().getResourcePackageName(R.drawable.profilepicnormall) + '/'
+ context.getResources().getResourceTypeName(R.drawable.profilepicnormall) + '/'
+ context.getResources().getResourceEntryName(R.drawable.profilepicnormall) )
lifecycleScope.async(Dispatchers.Main) {
async {
create(email,password)
}.await()
Log.d(TAG,"The isOk is $isOk")
if(isOk){
async {
Log.d(TAG,"in 1 async")
uploadImage()
}.await()
async {
Log.d(TAG,"in 2 async")
uploadDataToRealtimeDatabase(userUID,email,name,imageUrl)
}.await()
binding.pbSignup.visibility = View.GONE
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
finish()
}
binding.pbSignup.visibility = View.GONE
}
}
suspend fun create(email: String,password: String) {
Log.d(TAG,"BEFORE")
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(parent) {task ->
if(task.isSuccessful) {
Toast.makeText(this#SignUpActivity,"SignUp Successful.",Toast.LENGTH_SHORT).show()
isOk = true;
userUID = firebaseAuth.currentUser!!.uid
Log.d(TAG,"INSIDE")
return#addOnCompleteListener
}
else {
Log.d(TAG,"${task.exception} . ")
Toast.makeText(this#SignUpActivity,"SignUp Not Successful.",Toast.LENGTH_SHORT).show()
}
}
Log.d(TAG,"AFTER")
}
suspend fun uploadDataToRealtimeDatabase(UID:String,userEmail: String,userName : String,url:String) {
Log.d(TAG,"in upload data")
val ref = FirebaseDatabase.getInstance("https://firechat-931d2-default-rtdb.asia-southeast1.firebasedatabase.app/")
.getReference("/users/$UID")
val userinfo = UserInfo(userEmail,UID,userName,url)
ref.setValue(userinfo).addOnSuccessListener {
Log.d(TAG,"UPLOADED USER INFORMATION")
}.addOnFailureListener{
Log.d(TAG,"${it.message} $it")
}
}
suspend fun uploadImage() : String {
Log.d(TAG,"in upload Image")
val profilePicName = "${firebaseAuth.uid}.profileImage"
var url = "."
val storage_reference = FirebaseStorage.getInstance("gs://firechat-931d2.appspot.com").getReference("/ProfileImages/$profilePicName")
storage_reference.putFile(selectedPhoto!!).continueWithTask { task ->
if (!task.isSuccessful) {
Log.d(TAG,"${task.exception}")
}
storage_reference.downloadUrl.addOnSuccessListener {
url = it.toString()
}.addOnFailureListener{
Log.d(TAG,"$it ${it.message}")
}
}
if(url.length < 2) {
Log.d(TAG,"Going with default url.")
url = "https://firebasestorage.googleapis.com/v0/b/firechat-931d2.appspot.com/o/ProfileImages%2FsqE6s03wgXQm7gl03xxQIM3JVQc2.profileImage?alt=media&token=640266a5-6611-4e09-b8ed-72ba8bdfdc1f"
}
Log.d(TAG,"returning the img url $url")
return url
}
}
I implemented only the signup part in a dummy app after fixing some issues with your code, here are my observations:
No other statement
My logs were as follows:
D/SIGNUPATAG: STARTING PROCESS
D/SIGNUPATAG: INSIDE
D/SIGNUPATAG: The isOk is true
D/SIGNUPATAG: in 1 async
D/SIGNUPATAG: in upload Image
D/SIGNUPATAG: in 2 async
D/SIGNUPATAG: in upload data
I think I am using coroutines correctly but I don't know why this program doesn't go further than this ^. Should I use callbacks? Am I using coroutines in a wrong way?
I don't think you're using coroutines as intended, Firebase calls are already asynchronous so you don't require to do it this way, you should use Firebase coroutines instead which have built-in support for this case. I am adding the changes that I made below. (Omitting the stuff that doesn't require any change)
build.gradle
//firebase coroutines dependency
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.4.2"
SignUpActivity.kt
class SignUpActivity : AppCompatActivity() {
private lateinit var binding: ActivitySignUpBinding
.
.
override fun onCreate(savedInstanceState: Bundle?) {
.
.
}
private fun createAccount(email : String, password : String,name:String) {
lifecycleScope.launch(Dispatchers.Main) {
val createdUserJob = launch {
try {
Toast.makeText(this#SignUpActivity,"SignUp Successful.",Toast.LENGTH_SHORT).show()
isOk = true;
userUID = firebaseAuth.currentUser!!.uid
Log.d(TAG,"INSIDE")
firebaseAuth.createUserWithEmailAndPassword(email, password).await()
} catch (e: Exception) {
Toast.makeText(this#SignUpActivity,"SignUp Not Successful.",Toast.LENGTH_SHORT).show()
e.printStackTrace()
}
}
createdUserJob.join()
Log.d(TAG,"The isOk is $isOk")
if(isOk){
val uploadImageJob = launch {
Log.d(TAG,"in 1 async")
uploadImage()
}
uploadImageJob.join()
val uploadDataJob = launch {
Log.d(TAG,"in 2 async")
uploadDataToRealtimeDatabase(userUID,email,name,imageUrl)
}
uploadDataJob.join()
binding.pbSignup.visibility = View.GONE
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
finish()
}
binding.pbSignup.visibility = View.GONE
}
}
suspend fun uploadDataToRealtimeDatabase(UID:String,userEmail: String,userName : String,url:String) {
Log.d(TAG,"in upload data")
.
.
}
suspend fun uploadImage() : String {
Log.d(TAG,"in upload Image")
.
.
return "dummy"
}
}
Note: I have only tested the signup part, you need to test the image upload and upload data part on your own, I've removed the create(email: String,password: String) method as well.

Login button needs to be clicked twice to login

i'm making an app on AndroidStudio and I need to verify credentials when they log in to the app. The app works with an API and to verifiy credentials i created this function in the database to check someones email and password:
(postgresql)
create or replace function login (emailf text, passwordf text)
returns boolean
language plpgsql
as
$$
declare pp text;
begin
pp = (select pass_w from utilizador where utilizador.email = emailf);
if (pp = passwordf) then return true;
else return false;
end if; end
$$
I'm parsing the data through this CheckLoginas function:
var bola: Boolean? = null
fun CheckLoginas(c: Context?, email: String, pass: String): Boolean? {
var mQueue: RequestQueue
mQueue = Volley.newRequestQueue(c);
var url = "https://myurl.com" + "/utilizador/login/" + email + "/" + pass
val request = JsonArrayRequest(Request.Method.GET, url, null, Response.Listener {
response ->try {
var jsonArray = JSONArray()
jsonArray = response.getJSONArray(0)
for (i in 0 until jsonArray.length())
{
val jsonObject : JSONObject? = jsonArray.getJSONObject(i)
//val user = jsonArray.getJSONObject(i)
//val bool = jsonObject.getBoolean("login")
val boo : Boolean = jsonObject!!.getBoolean("login")
println("im inside CheckLoginas boo $boo\n\n")
bola = boo
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, Response.ErrorListener { error -> error.printStackTrace() })
mQueue?.add(request)
return bola
}
'bola' variable is a global variable because I needed to return a boolean from the function so I can know if the credentials check (or not) in another activity.
The Problem:
To login when the credentials are correct, I have to press twice in the login button. If the email and password are correct, the first time I press it gives me the "Wrong credentials" error and in the second time it logs in. I already tried to do it with a while(), I checked it step by step and it seems fine, nothing seems to work to fix this error... The function works, the API too, and the app itself kinda works too, it just has this bug of clicking twice on the button... This is the activity code:
package com.example.crowdzero
import CheckLoginas
import Database
import android.content.Intent
import android.os.Bundle
import android.view.View.OnFocusChangeListener
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.textfield.TextInputLayout
import java.lang.Thread.sleep
class Login : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val log_in_btn_log_in = findViewById<Button>(R.id.log_in_btn_log_in)
val log_in_btn_registar = findViewById<Button>(R.id.log_in_btn_registar)
log_in_btn_log_in.setOnClickListener {
verificacao()
}
log_in_btn_registar.setOnClickListener {
val intent = Intent(this, Registo::class.java)
startActivity(intent)
}
}
private fun verificacao() {
val log_in_input_text_email = findViewById<TextInputLayout>(R.id.log_in_input_text_email)
val log_in_input_text_password = findViewById<TextInputLayout>(R.id.log_in_input_text_password)
val string_email = log_in_input_text_email?.getEditText()?.getText().toString()?.trim()
val string_password = log_in_input_text_password?.getEditText()?.getText().toString()?.trim()
if (string_email.isNullOrEmpty())
{
log_in_input_text_email.setError(" ")
}
else if (string_password.isNullOrEmpty())
{
log_in_input_text_password.setError(" ")
}
else
{
val email = log_in_input_text_email.editText?.text.toString()
val password = log_in_input_text_password.editText?.text.toString()
//var baca = CheckLoginas(this,email,password)
println(email)
println(password)
var baca: Boolean? = null
baca = CheckLoginas(this, email, password)
//baca = CheckLoginas(this,email,password)
if (baca == false) {
//Toast.makeText(this, "Esta conta não está registada", Toast.LENGTH_SHORT).show();
println("Im inside if in login baca $baca")
} else if (baca == true) {
Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
val intent = Intent(this, Home::class.java)
startActivity(intent)
finish()
}
}
}
}
When I test this with an actual email and password from the database, baca variable stays false when it should be true, since CheckLoginas boo var is true. This is what is causing the problem.
image that shows it
I'm fairly new to the Database-API-App thing, so please forgive me if its a trivial thing
You are calling baca = CheckLoginas(this, email, password)
baca will not update immedietly, the next line if (baca == false) will be executed before you API response arrives, so after you got some response baca becomes true. This is why you need to click twice.
SOLVED:
I pretty much inserted the CheckLoginas function inside the login.kt file. It works now! It looks like this now:
package com.example.crowdzero
import Database
import android.content.Intent
import android.os.Bundle
import android.view.View.OnFocusChangeListener
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.textfield.TextInputLayout
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.lang.Thread.sleep
class Login : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val log_in_btn_log_in = findViewById<Button>(R.id.log_in_btn_log_in)
val log_in_btn_registar = findViewById<Button>(R.id.log_in_btn_registar)
log_in_btn_log_in.setOnClickListener {
verificacao()
}
log_in_btn_registar.setOnClickListener {
val intent = Intent(this, Registo::class.java)
startActivity(intent)
}
}
private fun verificacao() {
val log_in_input_text_email = findViewById<TextInputLayout>(R.id.log_in_input_text_email)
val log_in_input_text_password = findViewById<TextInputLayout>(R.id.log_in_input_text_password)
val string_email = log_in_input_text_email?.getEditText()?.getText().toString()?.trim()
val string_password = log_in_input_text_password?.getEditText()?.getText().toString()?.trim()
if (string_email.isNullOrEmpty())
{
log_in_input_text_email.setError(" ")
}
else if (string_password.isNullOrEmpty())
{
log_in_input_text_password.setError(" ")
}
else
{
val email = log_in_input_text_email.editText?.text.toString()
val password = log_in_input_text_password.editText?.text.toString()
var mQueue: RequestQueue
mQueue = Volley.newRequestQueue(this);
var url = "https://myurl.com" + "/utilizador/login/" + email + "/" + password
val request = JsonArrayRequest(Request.Method.GET, url, null, Response.Listener {
response ->try {
var jsonArray = JSONArray()
jsonArray = response.getJSONArray(0)
for (i in 0 until jsonArray.length())
{
val jsonObject : JSONObject? = jsonArray.getJSONObject(i)
//val user = jsonArray.getJSONObject(i)
//val bool = jsonObject.getBoolean("login")
val boo : Boolean = jsonObject!!.getBoolean("login")
println("im inside CheckLoginas boo $boo\n\n")
if (boo == false) {
Toast.makeText(this, "Esta conta não está registada", Toast.LENGTH_SHORT).show();
} else if (boo == true) {
Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
val intent = Intent(this, Home::class.java)
startActivity(intent)
finish()
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, Response.ErrorListener { error -> error.printStackTrace() })
mQueue?.add(request)
}
}
}

How do I get specific information from a registered user and display it in my app in Kotlin with Firebase?

I'm new to Kotlin and Firebase, I want this to happen:
When a registered user logs in with his Email and Password, I want to display the Complete Name (User has to input complete name upon registering) connected to that Email in my dashboard (new activity), How do I do it?
Relevant Codes:
MainActivity.kt:
lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser
if (currentUser != null) {
val intent = Intent(this#MainActivity, dashboard::class.java)
startActivity(intent)
finish()
}
login()
}
private fun login() {
loginButton.setOnClickListener {
if (TextUtils.isEmpty(emailLogin.text.toString())) {
emailLogin.error = "Please enter registered email."
return#setOnClickListener
} else if (TextUtils.isEmpty(passwordLogin.text.toString())) {
passwordLogin.error = "Please enter password."
return#setOnClickListener
}
auth.signInWithEmailAndPassword(emailLogin.text.toString(), passwordLogin.text.toString())
.addOnCompleteListener {
if (it.isSuccessful) {
val intent = Intent(this#MainActivity, dashboard::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(
this#MainActivity,
"Login failed, please try again! ",
Toast.LENGTH_LONG
).show()
}
}
}
dashboard.kt (idk if this is relevant):
lateinit var auth: FirebaseAuth
lateinit var toggle: ActionBarDrawerToggle
var databaseReference: DatabaseReference? = null
var database: FirebaseDatabase? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
val actionBar = supportActionBar
actionBar!!.title = "Dashboard"
auth = FirebaseAuth.getInstance()
database = FirebaseDatabase.getInstance()
databaseReference = database?.reference!!.child("profile")
toggle = ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
nv.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.profile -> Toast.makeText(applicationContext, "Clicked Profile", Toast.LENGTH_SHORT).show()
R.id.settings -> Toast.makeText(applicationContext, "Clicked Settings", Toast.LENGTH_SHORT).show()
R.id.logoutButton -> logout()
}
true
}
}
private fun logout() {
auth.signOut()
startActivity(Intent(this#dashboard, MainActivity::class.java))
finish()
}
I want the complete name to be displayed in this:
<TextView
android:id="#+id/completeNameDisplay"
android:layout_width="match_parent"
android:layout_height="132dp"
android:layout_marginStart="15dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="15dp"
android:background="#drawable/dashboard_modules"
android:padding="10dp"
android:paddingStart="25dp"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
Registration snippet:
private fun register(){
registerButton.setOnClickListener {
if(TextUtils.isEmpty(fullNameRegister.text.toString())) {
fullNameRegister.setError("Please enter full name")
return#setOnClickListener
} else if(TextUtils.isEmpty(phoneNumberRegister.text.toString())) {
phoneNumberRegister.setError("Please enter a valid phone number")
return#setOnClickListener
} else if(TextUtils.isEmpty(passwordRegister.text.toString())) {
passwordRegister.setError("Please enter password")
return#setOnClickListener
} else if(TextUtils.isEmpty(regionRegister.text.toString())) {
passwordRegister.setError("Please enter Region")
return#setOnClickListener
} else if(TextUtils.isEmpty(cityRegister.text.toString())) {
passwordRegister.setError("Please enter City")
return#setOnClickListener
} else if(TextUtils.isEmpty(address1Register.text.toString())) {
passwordRegister.setError("Please enter address")
return#setOnClickListener
} else if(TextUtils.isEmpty(address2Register.text.toString())) {
passwordRegister.setError("Please enter address")
return#setOnClickListener
} else if(TextUtils.isEmpty(emailRegister.text.toString())) {
passwordRegister.setError("Please enter email")
return#setOnClickListener
}
auth.createUserWithEmailAndPassword(emailRegister.text.toString(), passwordRegister.text.toString())
.addOnCompleteListener{
if(it.isSuccessful){
val currentUser = auth.currentUser
val currentUSerDb = databaseReference?.child((currentUser?.uid!!))
currentUSerDb?.child("Fullname")?.setValue(fullNameRegister.text.toString())
Toast.makeText(this#registration, "Registration Success! ", Toast.LENGTH_LONG).show()
finish()
} else {
Toast.makeText(this#registration, "Registration failed, please try again! ", Toast.LENGTH_LONG).show()
}
}
}
}
As discussed in the comments, it sounds like the code is working as you expect. In that case, I'm going to assume that the user is registered with Firebase Auth upon log in. If that's true, you should be able to access the current user as discussed in the documentation here: https://firebase.google.com/docs/auth/android/manage-users#get_a_users_profile
val user = Firebase.auth.currentUser
user?.let {
// Name, email address, and profile photo Url
val name = user.displayName
val email = user.email
val photoUrl = user.photoUrl
// Check if user's email is verified
val emailVerified = user.isEmailVerified
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
val uid = user.uid
}

How to return boolean from logining user

Hello I am doing mvvm project in kotlin and I use room to login and register new user.
Part of code:
view.login_btn.setOnClickListener {
val takenUsername = username.text.toString()
val takenPassword = password.text.toString()
if(takenUsername.isEmpty() || takenPassword.isEmpty()){
Toast.makeText(context, "Fill all columns", Toast.LENGTH_SHORT).show()
}else{
//Zwraca unity (naprawic to a nie null
val userEntity = mMainActivityViewModel.checkLogin(takenUsername,takenPassword)
if(userEntity.equals(null)){
Toast.makeText(context!!, "Bad login or password", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(context!!, "Login successfull", Toast.LENGTH_SHORT).show()
}
}
}
I dont understand why but this function returns a unit not a null.Which i completly doesnt know.
Could someone propose what should I put instead of null in line 11?
You are following wrong approach my friend. You need to use live data to get the callback from view model.
private fun setupLoginObserver() {
mMainActivityViewModel.loginStatus.observe(this, Observer { isValidUser ->
if (isValidUser) {
Toast.makeText(requireContext(), "Login successful", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(requireContext(), "Bad login or password", Toast.LENGTH_SHORT).show()
}
})
}
You can call this method from onViewCreated()
Your button click listener should be like:
view.login_btn.setOnClickListener {
val takenUsername = username.text.toString()
val takenPassword = password.text.toString()
if (takenUsername.isEmpty() || takenPassword.isEmpty()) {
Toast.makeText(context, "Fill all columns", Toast.LENGTH_SHORT).show()
} else {
//Check user is valid or not in db and you will get the callback on line #
mMainActivityViewModel.checkLogin(takenUsername, takenPassword)
}
}
ViewModel:
fun checkLogin(username: String, password: String) {
viewModelScope.launch(Dispatchers.IO) {
repository.loginUser(username, password)?.let {
mutableLoginStatus.postValue(true)
} ?: mutableLoginStatus.postValue(false)
}
}
UserRepository:
suspend fun loginUser(username: String, password: String): User? {
return userDao.loginUser(username, password)
}
And Finally UserDao:
#Query("SELECT user_table.* FROM user_table WHERE username= :username AND password=:password")
suspend fun loginUser(username: String, password: String): User?
I have made few required changes in your code and pushed in this branch.
https://github.com/parmeshtoyou/Querto/tree/user_validate_through_live_data_stackoverflow
You can review the changes.
Let me know if you need any clarification.
Happy Coding.
You can use a function to return a boolean, like this
view.login_btn.setOnClickListener {
loginUser()
}
fun loginUser():Boolean{
val takenUsername = username.text.toString()
val takenPassword = password.text.toString()
if(takenUsername.isEmpty() || takenPassword.isEmpty()){
Toast.makeText(context, "Fill all columns", Toast.LENGTH_SHORT).show()
return false
}else{
//Zwraca unity (naprawic to a nie null
val userEntity = mMainActivityViewModel.checkLogin(takenUsername,takenPassword)
if(userEntity.equals(null)){
Toast.makeText(context!!, "Bad login or password", Toast.LENGTH_SHORT).show()
return false
}else{
Toast.makeText(context!!, "Login successfull", Toast.LENGTH_SHORT).show()
return true
}
}
}
}
In MVVM Architecture we can use LiveData, To get the value from ViewModel
In ViewModel, we can validate the Login success or not,
fun checkLogin(username: String, password: String) {
// Perform Login validation
validUser.setValue(true) // set the livedata as true on login validation Success
validUser.setValue(false) // set the livedata as true on login validation falied
}
Inactivity you can Observe the LivedataChanges
mMainActivityViewModel.validUser.observe(this, Observer<Boolean> {validUser:Boolean? ->
if(validUser){
Toast.makeText(this, "Login successfull", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(this, "Login Failed", Toast.LENGTH_SHORT).show()
}
})
In OnClickListener
view.login_btn.setOnClickListener {
val takenUsername = username.text.toString()
val takenPassword = password.text.toString()
if(takenUsername.isEmpty() || takenPassword.isEmpty()){
Toast.makeText(context, "Fill all columns", Toast.LENGTH_SHORT).show()
}else{
// just call the method and set the Livedata value based on the validation
mMainActivityViewModel.checkLogin(takenUsername,takenPassword)
}
}

Check if EditText is empty kotlin android

How do you check if an EditText is empty? input type number
package com.example.www.myapplication
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
val inter:Int=editText.text.toString().toInt()
val year: Int = Calendar.getInstance().get(Calendar.YEAR)
val res:Int=year-inter
textView.text=res.toString()
}
}
Harness Kotlin power by using inline extension functions:
editText.text.isNotEmpty().apply {
//do something
}
or use let
Here is the full example with explanation.
//init the edittext
val etMessage = findViewById(R.id.et_message) as EditText
//init the button
val btnClick = findViewById(R.id.btn_click) as Button
btnClick.setOnClickListener{
//read value from EditText to a String variable
val msg: String = etMessage.text.toString()
//check if the EditText have values or not
if(msg.trim().length>0) {
Toast.makeText(applicationContext, "Message : "+msg, Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(applicationContext, "Please enter some message! ", Toast.LENGTH_SHORT).show()
}
}
You can be done by below way
if (mEdtDeviceName.text.toString().trim().isNotEmpty() ||
mEdtDeviceName.text.toString().trim().isNotBlank()) {
// your code
} else {
Toast.makeText(activity, "Error Msg", Toast.LENGTH_SHORT).show()
}
Hey I am using like this in kotlin
val input = editText?.text.toString().trim()
if (input.isNullOrBlank()) {
//Your code for blank edittext
}
Hope this will help you..let me know if any issue....
try this out:
bottom.setOnClickListener{
val new = addText.text.toString()
if (new = isNotEmpty()) {
//do something
} else {
Toast.makeText(context, "Enter some message ", Toast.LENGTH_SHORT).show()
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnSignUp : Button = findViewById(R.id.signUp)
val et_username : EditText = findViewById(R.id.etUsername)
val et_email : EditText = findViewById(R.id.etEmail)
val et_password : EditText = findViewById(R.id.etPassword)
btnSignUp.setOnClickListener{
val user_msg_error: String = et_username.text.toString()
//check if the EditText have values or not
if(user_msg_error.trim().isEmpty()) {
et_username.error = "Required"
Toast.makeText(applicationContext, "User Name Required ", Toast.LENGTH_SHORT).show()
}
else if (et_email.text.toString().trim().isEmpty()) {
et_email.error = "Required"
Toast.makeText(applicationContext, "Email Required ", Toast.LENGTH_SHORT).show()
}
else if (et_password.text.toString().trim().isEmpty()) {
et_password.error = "Required"
Toast.makeText(applicationContext, "Password Required ", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(applicationContext, "Login Successful ", Toast.LENGTH_SHORT).show()
// After successful login u will move on next page/ activity
val i = Intent(this,SecondActivity::class.java)
startActivity(i)
}
}
}
}
Try this:
if(TextUtils.isEmpty(editText.getText().toString())){
//Do
}
Been a new guy Tried lots and this Worked for me
if(!editTextTerminalName.text.toString().trim().isNotEmpty()) {
editTextTerminalName?.error = "Required"
}else if(!editTextPassword.text.toString().trim().isNotEmpty()){
editTextPassword?.error = "Required"
}else{
avi.visibility= View.VISIBLE // v letter should be capita
}
if (regemail.isEmpty())
{
Toast.makeText(this,"Enter Email..!!!",Toast.LENGTH_LONG).show()
}
Same solution but using class TextUtil and .isEmpty(charsequence:)
btnGo.setOnClickListener{
val input1 = etName.text.toString.trim() // 1
if(TextUtils.isEmpty(input1)){ // 2
etName.error = "Enter a name" // 3
return#setOnClickListener //4
}
//code to store a Bundle or insert in a sqlitedb etc
// go to secondactiviy
}
user only typed spacebars??? .trim() helps with that
TextUtil is a class .isEmpty one of its methods
displays a clickable red (!) in the EditText and when it is pressed displays "Enter a name" of course you can use getString(R.string.somename)
restarts onclicklistener / "restricts" some actions like change to other acivity, avoinding (for example) passing null a bundle() or insert a null in a db
Just do this, i was facing the same issue. :)
button.setOnClickListener {
val checkUsername = userName.text.toString()
if (checkUsername.isNullOrBlank()) {
Toast.makeText(context, "Please enter your name", Toast.LENGTH_SHORT).show()
} else {
val action = UserLoginFragmentDirections.actionUserLoginFragmentToBmiFragment()
findNavController().navigate(action)
}
}

Categories

Resources