How can I fix this? cant put setError to my editText - android

I make my first android app with Android Studio, and now I want to make a setError on my editText, but I cant, I only can put a toast
here is my code:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.calculateButton.setOnClickListener { calculateTip() }
}
private fun calculateTip() {
val stringInTextField = binding.costOfProduct.text.toString()
val stringInTextField1 = binding.amountOfProduct.text.toString()
if (stringInTextField.isEmpty()) {
Toast.makeText(this, "this cant be empty", Toast.LENGTH_SHORT).show()
return
}
val cost = stringInTextField.toDouble() / stringInTextField1.toDouble()
val tipPercentage = when (binding.productOptions.checkedRadioButtonId) {
R.id.option_normal -> 1.5
R.id.option_60 -> 1.6
R.id.option_70 -> 1.7
else -> 2.0
}
var product = tipPercentage * cost
val roundUp = binding.IVA.isChecked
if (roundUp) {
product = (tipPercentage * cost) * 1.21
}
val formattedTip = NumberFormat.getCurrencyInstance().format(product)
binding.result.text = getString(R.string.resultado, formattedTip)
}
}

You should use to setError()
Like this: stringInTextField.setError("this cant be empty")
For more information: Show Error on the tip of the Edit Text Android

you can use this following code according to your code:
if (stringInTextField.isEmpty()) { stringInTextField.setError("this cant be empty") return; }

Related

Kotlin App Keeps crashing immediately when running

I am very new to programming in general and I have just started coding in Kotlin in Android Studio. I'm trying to build a simple "Check if number is even or odd" app but I'm not sure where I'm going wrong.
My app crashes immediately when I start it up on the emulator.
class MainActivity : AppCompatActivity() {
private lateinit var enternumber : EditText
private lateinit var button: Button
private lateinit var output: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
enternumber = findViewById(R.id.et_number)
button = findViewById(R.id.btn_click)
output = findViewById(R.id.tv_output)
val enternum: Int = enternumber.text.toString().toInt()
button.setOnClickListener {
if (enternum % 2 == 0)
output.text = ("Number is even")
else
output.text = ("Number is odd")
}
}
}
Any help is greatly appreciated.
First, learn to use the logcat to get helpful exception stacktraces for problem diagnosis. Unfortunately MyApp has stopped. How can I solve this?
One problem here is obvious. Move the
val enternum: Int = enternumber.text.toString().toInt()
inside the onclick listener. At onCreate() phase there's no content in the edittext and toInt() will surely fail. Upon click there might be a number.
Your app keeps crashing due to this:
val enternum: Int = enternumber.text.toString().toInt()
You have to create two number vals. One to display as a String, and one to use as an Int in your if statement that is combined with the String.
Here is some code that will accomplish what you are trying to do. I put it into a function just to make it more readable:
class MainActivity : AppCompatActivity() {
private lateinit var enternumber: EditText
private lateinit var button: Button
private lateinit var output: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.btn_click)
output = findViewById(R.id.tv_output)
button.setOnClickListener {
getEvenOrOdd()
}
}
fun getEvenOrOdd() {
enternumber = findViewById(R.id.et_number)
val displayNumber = enternumber.text.toString()
val newNum = displayNumber.toInt()
val even = "Number is even"
val odd = "Number is odd"
if (newNum % 2 == 0) {
output.text = even
} else {
output.text = odd
}
}
}

Realm Kotlin - Delete realm object

https://www.mongodb.com/docs/realm/sdk/kotlin/realm-database/delete/delete-all-objects-of-a-type/
I am learning new kotlin-realm in my project. But i dont know how to delete objects. It keep showing error Caused by: io.realm.internal.interop.RealmCoreNotInATransactionException: [5]: Must be in a write transaction
this is the code :
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val realm by lazy { (application as CustomApplication).realm }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
realm.writeBlocking {
copyToRealm(Buku(
name = "Perjuangan Menjual Baju"
))
copyToRealm(Buku(
name = "Perang Saudara"
))
}
val buku = realm.query<Buku>("name BEGINSWITH $0", "pera")
Log.i("AOEU", "buku = $buku")
CoroutineScope(Dispatchers.Main).launch {
val query = realm.query<Buku>().find()
realm.write {
delete(query)
}
}
}
}
After days of finding solution. I just realized that the only mistake in my code is
val query = realm.query().find()
Which is should be replaced with
val query = this.query().find()

How to achieve password error like this in TextInputLayout Android?

This is what I want to achieve. And please help me with the regex for the third error.
You need to use isErrorEnabled and error atributes of your TextInputLayout instance.
const val PASSWORD_PATTERN = ...// your regex
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.checkPasswordButton.setOnClickListener {
val password = binding.passwordEditText.text.toString()
val isPasswordValid =
Pattern.compile(PASSWORD_PATTERN).matcher(password).matches()
binding.passwordInputLayout.isErrorEnabled = !isPasswordValid
val passwordError = if (isPasswordValid) "" else
getString(R.string.invalid_password)
binding.passwordInputLayout.error = passwordError
}
}
}

Check if Input is empty doesnt work Kotlin

Hey guys i just started playing around with android studio and wanted to make an app that calculates the faculty of an input value. It works if i give it an Input Value but if not it crashes, so i tried to check if the input is empty but that didn´t solve the error. Here´s the code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Button = findViewById<Button>(R.id.button)
val Output = findViewById<TextView>(R.id.Output)
val Input = findViewById<TextView>(R.id.Input)
Button.setOnClickListener {
val num = Input.text.toString().toInt()
if(num.toString().isNotBlank()) {
var hilf = 1
for (i in 1..num.toString().toInt()) {
hilf *= i
}
Output.text = hilf.toString()
}
}
}
Do you guys have any idea how i could fix the problem?
First you check if the EditText is empty and then try to convert to Int:
if(!Input.text.toString().trim().isEmpty()) {
val num = Input.text.toString().toInt()
var hilf = 1
for (i in 1..num) {
hilf *= i
}
Output.text = hilf.toString()
}
Also you don't need
num.toString().toInt()
you can just use
1..num
because num's type is Int
you want to use the following:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Button = findViewById<Button>(R.id.button)
val Output = findViewById<TextView>(R.id.Output)
val Input = findViewById<TextView>(R.id.Input)
Button.setOnClickListener {
val num = Input.text.toString().toInt()
if(!Input.text.toString().isEmpty()) {
var hilf = 1
for (i in 1..num.toString().toInt()) {
hilf *= i
}
Output.text = hilf.toString()
}
}
}

Smart cast to 'TaskAdapter' is impossible, because 'recyclerView.adapter' is a complex expression

class TodoActivity: AppCompatActivity() {
var id = 0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_todo)
setSupportActionBar(toolbar1)
val taskList = ArrayList<Task>()
val task1 = Task(id++, "Task", "Make awesome Tasks", Date())
taskList.add(task1)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = TaskAdapter(taskList) {
toast("${it.title}Clicked")
}
fab.setOnClickListener {
taskList.add(Task(id++, "Task${id}", "Description for Task ${id}", Date()))
recyclerView.adapter.notifyDataSetChanged()
}
if (taskList.size > 0)
tvNotTask.visibility = View.GONE
else
tvNotTask.visibility = View.VISIBLE
}
private fun toast(msg: String) = Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
this is my code, and when I want to run my App I get this following error
Smart cast to 'TaskAdapter' is impossible, because 'recyclerView.adapter' is a complex expression
does anybody know what to do I also can add the Layout file if you need to know something from overthere

Categories

Resources