Check if EditText is empty kotlin android - 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)
}
}

Related

Firebase auth not successful

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!"
}
}
}
}

view binding isn't working on Button setOnClickListner... [*ERROR = Variable 'getOTPButton' is never used] (KOTLIN)

please check out this error. I have used view binding on this activity to save data in Firebase. I have used the If... else statement on setOnClickListner.
Code for the Activity:
class RegisterSelection : AppCompatActivity() {
private lateinit var binding: ActivityRegisterSelectionBinding
private lateinit var database: DatabaseReference
#SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegisterSelectionBinding.inflate(layoutInflater)
setContentView(binding.root)
setContentView(R.layout.activity_register_selection)
val checkPasswordTwo = findViewById<CheckBox>(R.id.checkPasswordTwo)
val passwordText = findViewById<EditText>(R.id.passwordText)
val confirmPassText = findViewById<EditText>(R.id.confirmPassText)
val fullName=findViewById<EditText>(R.id.fullName).text.toString()
val phoneNumberEdit=findViewById<EditText>(R.id.phoneNumberEdit).text.toString()
val getOTPButton = findViewById<Button>(R.id.getOTPButton)
binding.getOTPButton.setOnClickListener {
if(fullName.isEmpty() && phoneNumberEdit.isEmpty()){
Toast.makeText(applicationContext,"Fill all the Fields!",Toast.LENGTH_LONG).show()
}
else{
database = FirebaseDatabase.getInstance().getReference("UserDataClass")
val users = UserDataClass(fullName, phoneNumberEdit)
database.child(fullName).setValue(users).addOnSuccessListener {
binding.fullName.text.clear()
binding.phoneNumberEdit.text.clear()
Toast.makeText(applicationContext,"Success!",Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(applicationContext,"Failed to Save!",Toast.LENGTH_SHORT).show()
}
val intent = Intent(this, getOTP::class.java)
startActivity(intent)
}
}
checkPasswordTwo.setOnClickListener {
if (checkPasswordTwo.text.toString() == "Show Password"){
passwordText.transformationMethod = HideReturnsTransformationMethod.getInstance()
confirmPassText.transformationMethod = HideReturnsTransformationMethod.getInstance()
checkPasswordTwo.text = "Hide Password"
} else{
passwordText.transformationMethod = PasswordTransformationMethod.getInstance()
confirmPassText.transformationMethod = PasswordTransformationMethod.getInstance()
checkPasswordTwo.text = "Show Password"
}
}
}
}
build.gradle
buildFeatures{ viewBinding true }
UserDataClass
data class UserDataClass(val fullName: String? = null, val phoneNumberEdit: String? = null)
Output only shows the Toast "fill all the fields."
Any suggestions would be grateful.
I recommend,if(fullName.isEmpty() && phoneNumberEdit.isEmpty()) change this to if(fullName.isEmpty() || phoneNumberEdit.isEmpty()){ - you want to ensure that both are filled I assume.
Secondly, since you are using binding, I would also recommend that you check for null this way: binding.<edit text id>.text.isNullOrEmpty().
Lastly, it looks like you are initialising your text values by reading the text value in the edit text post inflation and not reading the values you have entered on button click. In your onClickListener, read the values from your editText and then check for null.

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 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)
}
}

How to resolve the error "LifecycleOwners must call register before they are STARTED"

I am using registerForActivityResult for google sign in implementation in my development. Everything was working fine until I upgraded my fragment dependency to 1.3.0-beta01. The application current crash with the error
java.lang.IllegalStateException: LifecycleOwner SignupChoicesFragment{8e0e269} (193105b9-afe2-4941-a368-266dbc433258) id=0x7f090139} is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
I have used the function before oncreate using lazy loading but it wont work still.
class SignupChoicesFragment : DaggerFragment() {
#Inject
lateinit var viewModelProviderFactory: ViewModelFactory
val userViewModel: UserViewModel by lazy {
ViewModelProvider(this, viewModelProviderFactory).get(UserViewModel::class.java)
}
#Inject
lateinit var mGoogleSignInClient:GoogleSignInClient
val arg:SignupChoicesFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_signup_choices, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
google_sign_in_button.setOnClickListener {
val intent = mGoogleSignInClient.signInIntent
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(), ActivityResultCallback {result->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
task.addOnCompleteListener {
if (it.isSuccessful) {
val account: GoogleSignInAccount? =
it.getResult(ApiException::class.java)
val idToken = it.result?.idToken
val email = account?.email
val lastName = account?.familyName
val firstName = account?.givenName
val otherName = account?.displayName
val imageUrl = account?.photoUrl
val category = arg.category
val newUser = User()
newUser.firstName = firstName
newUser.lastName = lastName
newUser.otherName = otherName
newUser.category = category
newUser.email = email
newUser.imageUrl = imageUrl.toString()
userViewModel.currentUser = newUser
newUser.token = idToken
i(title, "idToken $idToken")
requireActivity().gdToast("Authentication successful", Gravity.BOTTOM)
val action = SignupChoicesFragmentDirections.actionSignupChoicesFragmentToEmailSignupFragment()
action.newUser = newUser
goto(action)
} else {
requireActivity().gdToast(
"Authentication Unsuccessful",
Gravity.BOTTOM
)
Log.i(title, "Task not successful")
}
}
} else {
Log.i(title, "OKCODE ${Activity.RESULT_OK} RESULTCODE ${result.resultCode}")
}
}).launch(intent)
}
}
For me, the issue was that I was calling registerForActivityResult within an onClickListener which was only invoked on clicking a button (the app at this point is in state RESUMED). Moving the call outside the button's onClickListener and into the Activity's onCreate method fixed it.
quote from documentation
registerForActivityResult() is safe to call before your fragment or activity is created, allowing it to be used directly when declaring member variables for the returned ActivityResultLauncher instances.
Note: While it is safe to call registerForActivityResult() before your fragment or activity is created, you cannot launch the ActivityResultLauncher until the fragment or activity's Lifecycle has reached CREATED.
so to solve your issue move your register call outside the onCreate() and put it in fragment scope, and on google_sign_in_button click-listener call launch function
Note: if you are using Kotlin-Android-Extention move your click-listener call to onViewCreated()
If you are using a Fragment, please make sure that you are NOT performing the registerForActivityResult on the activity. Fragments also have a registerForActivityResult and that's the one you should use.
you must remove val launcher = registerForActivityResult... out of the setOnClickListener, then save it in a variable, in your example is launcher and in the setOnClickListener execute the variable with .launch, in your example es launcher.
your code would look like this
google_sign_in_button.setOnClickListener {
val intent = mGoogleSignInClient.signInIntent
launcher.launch(intent)
}
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(), ActivityResultCallback {result->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
task.addOnCompleteListener {
if (it.isSuccessful) {
val account: GoogleSignInAccount? =
it.getResult(ApiException::class.java)
val idToken = it.result?.idToken
val email = account?.email
val lastName = account?.familyName
val firstName = account?.givenName
val otherName = account?.displayName
val imageUrl = account?.photoUrl
val category = arg.category
val newUser = User()
newUser.firstName = firstName
newUser.lastName = lastName
newUser.otherName = otherName
newUser.category = category
newUser.email = email
newUser.imageUrl = imageUrl.toString()
userViewModel.currentUser = newUser
newUser.token = idToken
i(title, "idToken $idToken")
requireActivity().gdToast("Authentication successful", Gravity.BOTTOM)
val action = SignupChoicesFragmentDirections.actionSignupChoicesFragmentToEmailSignupFragment()
action.newUser = newUser
goto(action)
} else {
requireActivity().gdToast(
"Authentication Unsuccessful",
Gravity.BOTTOM
)
Log.i(title, "Task not successful")
}
}
} else {
Log.i(title, "OKCODE ${Activity.RESULT_OK} RESULTCODE ${result.resultCode}")
}
})
Source : https://medium.com/codex/android-runtime-permissions-using-registerforactivityresult-68c4eb3c0b61
registerForActivityResult() is safe to call before your fragment or activity is created, allowing it to be used directly when declaring member variables for the returned ActivityResultLauncher instances.
you should call registerForActivityResult before view created. member variables or onCreate()
If you are working with any third party library then it may happens that you can't see the "registerForActivityResult" in your code but it should be present in classes provided by that same library.
So in this case I will suggest to move out the lines which is related to that library from any listener to the onCreate method.
for example -
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final RoomBackup roomBackup = new RoomBackup(GoogleDriveActivity.this);
roomBackup.database(LocalDataBase.getInstance(getApplicationContext()));
roomBackup.enableLogDebug(true);
roomBackup.backupIsEncrypted(false);
roomBackup.backupLocation(RoomBackup.BACKUP_FILE_LOCATION_INTERNAL);
roomBackup.onCompleteListener((success, message, exitCode) -> {
Log.d(TAG, "success: " + success + ", message: " + message + ", exitCode: " + exitCode);
if (success) roomBackup.restartApp(new Intent(getApplicationContext(), GoogleDriveActivity.class));
});
roomBackup.restore();
}
});
//// remove other code from listener and shift in onCreate
roomBackup = new RoomBackup(GoogleDriveActivity.this);
roomBackup.database(LocalDataBase.getInstance(getApplicationContext()));
roomBackup.enableLogDebug(true);
roomBackup.backupIsEncrypted(false);
roomBackup.backupLocation(RoomBackup.BACKUP_FILE_LOCATION_INTERNAL);
roomBackup.maxFileCount(5);
roomBackup.onCompleteListener((success, message, exitCode) -> {
Log.d(TAG, "success: " + success + ", message: " + message + ", exitCode: " + exitCode);
if (success) roomBackup.restartApp(new Intent(getApplicationContext(), GoogleDriveActivity.class));
});
/// you can keep only required lines in listener
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
roomBackup.backup();
}
});
That's it!
Found the same issue and manage to get to work with some magic.
In my case, it was happening in an Activity, so I went about it as such:
//...other bits
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
// doing the setup here
setupViews()
}
private fun setupViews() {
val buttonLauncher = navigator.gotoScreenForResult(this) { success ->
if (success) {
setResult(Activity.RESULT_OK)
finish()
}
}
binding.myButton.setOnClickListener {
buttonLauncher.launch(Unit)
}
Where the navigator.gotoScreenForResult would look like the following:
override fun gotoScreenForResult(context: AppCompatActivity, callback: (Boolean) -> Unit): ActivityResultLauncher<Unit> {
val contract = object : ActivityResultContract<Unit, Boolean>() {
override fun createIntent(context: Context, input: Unit?): Intent {
return Intent(context, MyNextActivity::class.java)
}
override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
return resultCode == Activity.RESULT_OK
}
}
return context.registerForActivityResult(contract) { callback(it) }
}
Just make sure the setupViews is done within the onCreate and not on the resume step.

Categories

Resources