Kotlin Code to Validate a Confirmation of Password - kotlin

Need code to validate the confirmation of password, included is the validation of password field:
private fun passwordValidate(text: String?): Boolean {
var p = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[#\$!%*?&])[A-Za-z\\d#\$!%*?&]{5,20}\$")
var m = p.matcher(text)
return m.matches()
}
The confirm password I would guess would start of similar as follows:
private fun confirmpasswordValidate(text: String?): Boolean {
var p = Pattern.compile

I assume that you do not need any extra method to validate the confirmpassword. You should first check if the passwords are the same and if they are, then simply check the first password with your passwordValidate method.

Related

There's a cycle in the delegation calls chain error in Kotliln constructor

I create two secondary constructor in entity class in first
constructor I want to pass String values, and in second secondary
constructor I want to pass the entity class data but I get error in
first secondary constructor where I pass the String data
I get this type of error in UserEntity constructor
There's a cycle in the delegation calls chain
User.kt
package com.nilmani.mychat.model
import org.jetbrains.annotations.NotNull
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDate
#Document
open class User(
#Id
var id: String ="",
var userName:String="",
private var password:String="",
var email:String="",
var createdAt:LocalDate=LocalDate.now(),
var updatedAt:LocalDate= LocalDate.now(),
var active:Boolean=false,
#NotNull
var userProfile:Profile,
#NotNull
var role:MutableSet<Role> = HashSet()
) {
constructor(
userName: String,
password: String,
email: String,
) : this(userName,password,email){
this.userName= userName
this.password=password
this.email = email
}
constructor(user:User):
this(user.id,user.userName,
user.password,user.email,
user.createdAt,user.updatedAt,
user.active,user.userProfile,
user.role){
this.id=user.id,
this.userName=user.userName
this.password = user.password
this.email = user.email
this.createdAt = user.createdAt
this.updatedAt = user.updatedAt
this.active = user.active
this.userProfile = user.userProfile
this.role = user.role
}
}
I get error at this keyword on first constructor decleration
You are delegating to the same constructor, which forms a loop and causes the error.
From kotlin spec
If a class has a primary constructor, any secondary constructor must
delegate to either the primary constructor or to another secondary
constructor via this(...).
In all cases, it is forbidden if two or more secondary constructors
form a delegation loop.
To solve this try to call the primary constructor or the one that expects User object as argument
constructor(userName: String,
password: String,
email: String): this(userName = userName,
password = password,
email = email,
userProfile = someDefaultValue) {
}

Simple casting in Kotlin/Java

I have an object User defined as below
class User(){
var id: Int? = null
var name: String? = null}
For certain reasons, I have to create new object User of same parameters and I have to copy data from old to new type.
class UserNew(){
var id: Int? = null
var name: String? = null}
I was looking for easiest way to convert from old type to a new one. I want to do simply
var user = User()
var userNew = user as UserNew
But obviously, I am getting This cast can never succeed. Creating a new UserNew object and set every parameter is not feasible if I have a User object with lots of parameters. Any suggestions?
as is kotlin's cast operator. But User is not a UserNew. Therefore the cast fails.
Use an extension function to convert between the types:
fun User.toUserNew(): UserNew {
val userNew = UserNew()
userNew.id = id
userNew.name = name
return userNew
}
And use it like so
fun usingScenario(user: User) {
val userNew = user.toUserNew()
If you don't want to write a boilerplate code, you can use some libraries that will copy values via reflection (for example http://mapstruct.org/), but it's not the best idea.
To achieve you can Simply use Gson and avoid boilerplate code:
var user = User(....)
val json = Gson().toJson(user)
val userNew:UserNew =Gson().fromJson(json, UserNew::class.java)
you should follow this logic for this case.
note: #Frank Neblung answer i implemented
fun main(args: Array<String>) {
val user = User()
user.id = 10
user.name = "test"
var userNew = user.toUserNew()
println(userNew.id) // output is 10
println(userNew.name)// output is test
}
class User()
{
var id: Int? = null
var name: String? = null
fun toUserNew(): UserNew {
val userNew = UserNew()
userNew.id = id
userNew.name = name
return userNew
}
}
class UserNew() {
var id: Int? = null
var name: String? = null
}
You have two options. Either create interface and implement it in both classes. then you can use this interface in both places (User,UserNew) If this is not what you want, i would use copy constructor in UserNew taking User as parameter, You can create new
NewUser nu = new UserNew(userOld)
if you have lots of properties answer from ppressives is way to go
To achieve that you can use the concept of inheritance:
https://www.programiz.com/kotlin-programming/inheritance
Example:
open class Person(age: Int) {
// code for eating, talking, walking
}
class MathTeacher(age: Int): Person(age) {
// other features of math teacher
}

Cannot return a String in Kotlin when don't "private"

Why it error when i make userName is public:
Error:(2, 5) Kotlin: Platform declaration clash: The following
declarations have the same JVM signature
(getUserName()Ljava/lang/String;):
fun (): String defined in User
fun getUserName(): String defined in User
Error:(4, 5) Kotlin: Platform declaration clash: The following declarations have the same
JVM signature (getUserName()Ljava/lang/String;):
fun (): String defined in User
fun getUserName(): String defined in User
But i make userName is private is working fine
class User{
/*private*/ var userName: String = "Emily"
fun getUserName(): String{
return userName
}
}
fun main(args: Array<String>){
val User = User()
print(User.getUserName())
}
By making your userName property public, Kotlin will create corresponding getUserName() and setUserName() functions for you. When it does this, writing your own getUserName() is redundant - the same function with the same signature is effectively present twice - and the compiler won't allow it.
If you want the userName field to be a public property (with a generated getter and setter), then you can't also write the getter yourself. This would be adequate:
var userName: String = "Emily"
If you wanted userName to have a public getter and a private setter (which seems like what you intended), this is the Kotlin way to do that:
var userName: String = "Emily"
private set
And finally, you could still create custom accessors on a property (e.g., if you wanted extra logic, such as to return it lowercased). The Kotlin way to do that looks like this:
private var _userName: String = "Emily"
var userName: String
get() = _userName.toLowerCase()
set(value) { _userName = value }
Also, note that the way you access the property is different depending on whether you're accessing it from Kotlin or Java. From Kotlin, you just write user.userName, but in Java, you'd write user.getUserName().
When you define var userName you are really defining a property, not just a field. Along with the property comes an implicit getUserName() and setUserName() method. By adding your own getUserName(), you are shadowing the one Kotlin is creating for you automatically.
You can safely drop your getUserName() and the make your field non-private and it should work fine. The idiomatic way to write your code would be something like this:
class User {
var userName: String = "Emily"
}
fun main(args: Array<String>){
val user = User() // Note changed val from User to user.
print(user.userName) // Note, this really calls the getter
}
In Kotlin, a setter and getter is being created for every property (unless visibility prohibits it), e.g. for your userName which happens to be named exactly like the one you provided in addition: getUserName(). The result is a name clash. Note that for var, also setters are generated. Use val for read-only properties.
Actually, you don't need explicit getters like this. Simply do:
class User{
/*private*/ var userName: String = "Emily"
}
//use property syntax
val user = User()
print(user.userName)
I just want to add more about private field. When you declare a field with private modifier, Kotlin won't generate getter/setter
class User {
private var userName = "Na"
fun getUserName(): String {
return userName;
}
fun setUserName(v: String) {
userName = v
}
}
And when you declare above methods (getter and setter) then these are treated as User Defined methods.

Infinite recursion in Getter in Kotlin

I am familiar with Java, but I am having difficulty working with Kotlin.
To illustrate my question, here is some Java Code. If the getter finds the field to be NULL, it initializes the field, before returning the field.
package test;
public class InitFieldJava {
private final static String SECRET = "secret";
private String mySecret;
public String getMySecret() {
if(mySecret == null) initMySecret();
return mySecret;
}
private void initMySecret() {
System.out.println("Initializing Secret ....");
mySecret = SECRET;
}
public static void main(String[] args) {
InitFieldJava field = new InitFieldJava();
System.out.println(field.getMySecret());
}
}
Can I do something like the above in Kotlin. My attempt in Kotlin looks like this:
package test
class InitFieldKotlin {
private val SECRET = "secret"
private var mySecret: String? = null
get() {
if (mySecret == null) initMySecret() //Infinite Recursion!!!
return mySecret
}
private fun initMySecret() {
println("Initializing Secret ....")
mySecret = SECRET
}
companion object {
#JvmStatic
fun main(args: Array<String>) {
val field = InitFieldKotlin()
println(field.mySecret)
}
}
}
My problem is that this results in infinite recursion:
Exception in thread "main" java.lang.StackOverflowError
at test.InitFieldKotlin.getMySecret(InitFieldKotlin.kt:7)
at test.InitFieldKotlin.getMySecret(InitFieldKotlin.kt:7)
at test.InitFieldKotlin.getMySecret(InitFieldKotlin.kt:7)
at test.InitFieldKotlin.getMySecret(InitFieldKotlin.kt:7)
I’d appreciate knowing what I’m doing wrong.
Try to use field keyword inside get():
private var mySecret: String? = null
get() {
if (field == null) initMySecret()
return field
}
Generally speaking, field allows to access your value directly without calling get, almost in the same way as in your Java example. More information can be found in documentation.
The problem you're facing is that when you call your property this way, the getter will be called again. And when you call getter, another getter is called, and so on until an StackOverflow.
You can fix this as shown by #Google, and using field inside the getter, instead of the property name:
if (field == null)initMySecret()
This way you won't access the property using its getter.
But more importantly: why don't you use a lazy initialization? If the variable is final, and it seems to be, you could use a lazy val
This way, the field won't be nullable anymore, so you won't have to safe-call it. And you'll not use boilerplate code, Kotlin can do this lazy initialization for you!
val mySecret: String by lazy {
println("Initializing Secret. This print will be executed only once!")
"SECRETE" //This value will be returned on further calls
}
More examples on Lazy can be seen at Kotlin Docs

How to pass the values from activity to another activity

As I'm learning Kotlin for Android development, I'm now trying the basic programs like hello world and how to navigate from one activity to another activity, there is no issue with this.
When I move from one activity to another, it works fine, but I do not know how to pass the values between the activities.
I tried to set the values in one activity and retrieved them in another activity it does not work.
Please see the code snippet below
This is my main activity where I take the username and password from edit text and setting to the intent:
class MainActivity : AppCompatActivity() {
val userName = null
val password = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
val intent = Intent(this#MainActivity,SecondActivity::class.java);
var userName = username.textø
var password = password_field.text
intent.putExtra("Username", userName)
intent.putExtra("Password", password)
startActivity(intent);
}
}
}
This is my second activity where I have to receive values from the main activity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
var strUser: String = intent.getStringExtra("Username")
var strPassword: String = intent.getStringExtra("Password")
user_name.setText("Seelan")
passwor_print.setText("Seelan")
}
}
Please guide me on how to do this, whether I have some other way to do this in Kotlin if not by intent.
Send value from HomeActivity
val intent = Intent(this#HomeActivity,ProfileActivity::class.java)
intent.putExtra("Username","John Doe")
startActivity(intent)
Get values in ProfileActivity
val profileName=intent.getStringExtra("Username")
I'm on mobile, you must test by yourself.
Try to make a CharSequence to a String in MainActivity , you have put a CharSequence rather than a String, for example:
var userName = username.text.toString()
var password = password_field.text.toString()
In Kotlin, you can pass the data simply by using the Intents. You can directly put your data in intent or you can write those data in bundle and send that bundle to another activity using the intent.
val intent = Intent(this#HomeActivity,ProfileActivity::class.java);
intent.putExtra("profileName", "John Doe")
var b = Bundle()
b.putBoolean("isActive", true)
intent.putExtras(b)
startActivity(intent);
You can simply use the intents and bundle to send data from one activity to another activity.
val intent = Intent(this#OneActivity,TwoActivity::class.java);
intent.putExtra("username", userName)
startActivity(intent);
//On Click on Button
var but = findViewById<Button>(R.id.buttionActivity_two) as Button
but.setOnClickListener {
//Define intent
var intent = Intent(applicationContext,MainActivity::class.java)
// Here "first" is key and 123 is value
intent.putExtra("first",123)
startActivity(intent)
}
}
// If Get In Into Other Activity
var Intent1: Intent
Intent1= getIntent()
//Here first is key and 0 is default value
var obj :Int = Intent1.getIntExtra("first",0);
Log.d("mytag","VAlue is==>"+obj)
first you should do this,
var userName = username.text.toString()
var password = password_field.text.toString()
Add Anko dependency.
implementation "org.jetbrains.anko:anko:0.10.4"
information passing inside MainActivity() is like
startActivity<SecondActivity>("Username" to userName,"Password" to password )
get information from SecondActivity() is,
val profileName=intent.getStringExtra("Username")
You can just access the value without using extras or intent. Simply use companion object in MainActivity:
companion object{
val userName: String = String()
val password: String = String()
}
In SecondActivity:
var strUser: String = MainActivity.username
var strPassword: String = MainActivity.password
And you can access the values from multiple activities easily.
Send data
val Name=findViewById<EditText>(R.id.editTextTextPersonName)
val Name2=findViewById<EditText>(R.id.editTextTextPersonName2)
val name=Name.text.toString()
val age=Name2.text.toString()
val intent1=Intent(this,Second::class.java).also {
it.putExtra("Username",name)
it.putExtra("Age",age)
startActivity(it);
}
Receive data
val name=intent.getStringExtra ("Username")
val age = intent.getStringExtra("Age")
val textView5=findViewById<TextView>(R.id.textView).apply {
text= "Name = $name"
}
val textView6=findViewById<TextView>(R.id.textView2).apply {
text= "Age = $age"
}