Home > OS >  Kotlin Android Studio - "If" is not executing in correct condition
Kotlin Android Studio - "If" is not executing in correct condition

Time:01-06

I am trying to make a simple Kotlin program of sign in page. The concept here was that this page will get the intent extras coming from the register page and use them to verify if the user logged in with the same registered username and password which would then bring the user to the main page of the app. The problem is that when the user actually does put the correct input, the intent won't execute (or rather the if gate).

val intent = intent
val registeredUsername = intent.getStringExtra("RegisteredUsername").toString()
val registeredPassword = intent.getStringExtra("RegisteredPassword").toString()
val username = usernameInput.text.toString()
val userPass = passwordInput.text.toString()

signInbtn.setOnClickListener{

    Toast.makeText(applicationContext, "username is: $registeredUsername", Toast.LENGTH_LONG).show()
    Toast.makeText(applicationContext, "password is: $registeredPassword", Toast.LENGTH_LONG).show()
    if ((username == registeredUsername) && (userPass == registeredPassword))
    {
        val moveMainPage = Intent(this@SignIn, MainPage::class.java)
        startActivity(moveMainPage)
    }
    else
    {
        invalideUserText.visibility = View.VISIBLE
        invalidPassword.visibility = View.VISIBLE
    }

}

At first I thought that the nullsafe strings were the problem when I took the intent data from the register page and so I converted the variable into a string.

But it was still no bueno so I'm not sure what is the wrong here.

CodePudding user response:

You are initializing the username and userPass at creation of the screen so they will be always empty String. Try moving them to inside the listener so they actually will be read out when you click the button. Like

val intent = intent
val registeredUsername = intent.getStringExtra("RegisteredUsername").toString()
val registeredPassword = intent.getStringExtra("RegisteredPassword").toString()

signInbtn.setOnClickListener{
    val username = usernameInput.text.toString()
    val userPass = passwordInput.text.toString()

    Toast.makeText(applicationContext, "username is: $registeredUsername", Toast.LENGTH_LONG).show()
    Toast.makeText(applicationContext, "password is: $registeredPassword", Toast.LENGTH_LONG).show()
    if ((username == registeredUsername) && (userPass == registeredPassword))
    {
        val moveMainPage = Intent(this@SignIn, MainPage::class.java)
        startActivity(moveMainPage)
    }
    else
    {
        invalideUserText.visibility = View.VISIBLE
        invalidPassword.visibility = View.VISIBLE
    }

}
  • Related