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()
}
}
}
Related
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
}
}
}
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; }
I have created a 50 second timer. I want it to call another screen using an Intent after the timer ends. But I get an error saying
None of the following functions can be called with the arguments supplied.
(Context!, Class<*>!) defined in android.content.Intent
(String!, Uri!) defined in android.content.Intent
class NewGame : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_game)
val results = findViewById<TextView>(R.id.textView5)
val results2 = findViewById<TextView>(R.id.textView6)
val greater = findViewById<Button>(R.id.button3)
val equal = findViewById<Button>(R.id.button4)
val less = findViewById<Button>(R.id.button5)
val result = findViewById<TextView>(R.id.textView7)
val submit = findViewById<Button>(R.id.button7)
val counttime = findViewById<TextView>(R.id.textView8)
var great = ""
var equ = false
var les = false
var hasSubmitted = false
var answer = 0
var counter = 0
gameplay(results, results2, result, greater, equal, less)
val timer = object: CountDownTimer(50000, 1000) {
override fun onTick(millisUntilFinished: Long) {
counttime.setText((counter).toString());
counter++;
}
override fun onFinish() {
val endGameIntent = Intent(this, EndGame::java)
startActivity(endGameIntent)
}
}
timer.start()
}
You pass context to the Intent and in your case this in that scope refers to CountDownTimer.
val endGameIntent = Intent(this#NewGame , EndGame::java)
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
}
}
}
I am a beginner at Android Studio and KOTLIN. Please check out my problem.
Code:
class getOTP : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_get_otp)
val inputCode1 = findViewById<EditText>(R.id.inputCode1).text.toString()
val inputCode2 = findViewById<EditText>(R.id.inputCode2).text.toString()
val inputCode3 = findViewById<EditText>(R.id.inputCode3).text.toString()
val inputCode4 = findViewById<EditText>(R.id.inputCode4).text.toString()
val verifyOTPButtonOne = findViewById<Button>(R.id.verifyOTPButtonOne)
verifyOTPButtonOne.setOnClickListener {
if(inputCode1 == "" || inputCode2 == "" || inputCode3 == "" || inputCode4 == ""){
Toast.makeText(applicationContext,"Please Enter Correct OTP",Toast.LENGTH_SHORT).show()
}
else {
val intent = Intent(this, VerifySuccess::class.java)
startActivity(intent)
}
}
}
}
}
PROBLEM: Here, after inputting all 4 text fields the toast is still appearing and Activity is not starting.
You are reading the value of the text fields only once, at the moment you call .toString() on them. So the if in the onClickListener only checks the initial values of the text fields.
You would have to call .toString() inside the listener for it to react appropriately, or you could just call isEmpty() directly on the Editable since it implements CharSequence:
class getOTP : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_get_otp)
val inputCode1 = findViewById<EditText>(R.id.inputCode1)
val inputCode2 = findViewById<EditText>(R.id.inputCode2)
val inputCode3 = findViewById<EditText>(R.id.inputCode3)
val inputCode4 = findViewById<EditText>(R.id.inputCode4)
val verifyOTPButtonOne = findViewById<Button>(R.id.verifyOTPButtonOne)
verifyOTPButtonOne.setOnClickListener {
if(inputCode1.text.isEmpty() || inputCode2.text.isEmpty() || inputCode3.text.isEmpty() || inputCode4.text.isEmpty()){
Toast.makeText(applicationContext,"Please Enter Correct OTP",Toast.LENGTH_SHORT).show()
} else {
val intent = Intent(this, VerifySuccess::class.java)
startActivity(intent)
}
}
}
}