I am working on a database, which requires user to register and login. When the use registers, the data gets stored into a room database. For the registration purpose, Kotlin code is used. But I want to use a Object of java class inside that Kotlin code.
Therefore, my query is it possible to initialise an object of Java class inside a Kotlin code?
For example:
user.java
package ...
public class User {
/* The credentials of a user. */
String userName, password, bID;
/* Last message */
String lastMessage;
public User(String userName, String password, String bID, String lastMessage) {
this.userName = userName;
this.password = password;
this.bID = bID;
this.lastMessage = lastMessage;
}
....
}
package... import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import kotlinx.android.synthetic.main.activity_register.* class RegisterActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) // handler= DatabaseHelper(this) val handler= DatabaseHelper(this) User user = new user(); btnLogRegister.setOnClickListener { onBackPressed() } reg_button.setOnClickListener{ handler.insertUserData(reg_bluetooth_name.text.toString(),reg_username.text.toString(),reg_password.text.toString()) Toast.makeText(this,"Values Inserted", Toast.LENGTH_LONG).show() } } }
I want to insert the java class object inside the register .kt
Change
User user = new User( )
//to this line
val user = User ( )
You have to use data class in kotlin like below
data class User (
val userName : String = "",
val password : String = "",
val bID : String = "",
val lastMessage : String = ""
)
How to use it
reg_button.setOnClickListener{
handler.insertUserData(User(reg_bluetooth_name.text.toString(),reg_username.text.toString(),reg_password.text.toString()))
Toast.makeText(this,"Values Inserted", Toast.LENGTH_LONG).show()
}
For kotlin, use data class, and to enjoy more features of kotlin like checking for nullability make you class like this,
data class User (var userName : String?,var password : String?,var bID : String?,var lastMessage : String?
)
Using var enable use to get both setters and getters whereas val will only give you getters. Note that the
`User (var userName : String?,var password : String?,var bID : String?,var lastMessage : String?)`
is the primary constructor and you can create more.
And in you activity you can force unwrap the values as shown in the code or use default values.
reg_button.setOnClickListener{
handler.insertUserData(reg_bluetooth_name.text.toString()!,reg_username.text.toString()!,reg_password.text.toString()!)
Toast.makeText(this,"Values Inserted", Toast.LENGTH_LONG).show()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.