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
}
}
}
Related
My AndroidManifest.xml does not include anything that would cause this (that I know of).
I.e. it does not include:
android:configChanges="orientation"
Android Version: Chipmunk 2021.2.1 Patch 1
class MainActivity : AppCompatActivity() {
internal lateinit var tapMeButton: Button
internal lateinit var gameScoreTextView: TextView
internal lateinit var timeLeftTextView: TextView
internal var score: Int = 0
internal var gameStarted = false
internal lateinit var countDownTimer: CountDownTimer
internal val initialCountDown: Long = 5000
internal val countDownInterval: Long = 1000
companion object {
private val TAG = MainActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "onCreate called. Score is $score")
tapMeButton = findViewById(R.id.tapMeButton)
gameScoreTextView = findViewById(R.id.gameScoreTextView)
timeLeftTextView = findViewById(R.id.timeLeftTextView)
tapMeButton.setOnClickListener { view ->
if (!gameStarted) {
startGame()
}
incrementScore()
}
resetGame()
}
It's hard to help you without seeing your code. But check that is this line available in your code.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Maybe be you don't activate rotation in the top panel of your simulator.
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 am really new to Android Studio(I just started yesterday) and I'm coding a sort of clicker game(in XML and kotlin).
I wanted the click counter (which is in a textview with a text at the begining) to save when leaving the app and loading when launching. I looked up savepreferences but I don't really understand how it works .. Could you guys help me please ?
`class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
var mCounter = 0
var txv = findViewById<TextView>(R.id.tx)
one.setOnClickListener {
//Play sound when click
mp.start()
//Increment click counter
mCounter++
txv.text = "Fixed mistakes: " + mCounter.toString()
}
}
}`
Any help is welcomed :)
EDIT: I posted some code that i did with savedpreferences but it is not fully functionnal. I would gladly appreciate some help ^^
EDIT V2: look at the comments for the solution
EDIT V2: I did it, here is the code
`class MainActivity : AppCompatActivity() {
//Counter lateinit initialisation
var mCounter by Delegates.notNull<Int>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Load la sauvegarde
loadData()
val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
var txv = findViewById<TextView>(R.id.tx)
//ON CLICK
one.setOnClickListener {
//Play le son quand on clique
mp.start()
//Compteur de click
mCounter++
txv.text = "Fixed mistakes: $mCounter"
saveData()
}
}
private fun saveData() {
val sharedPreferences = getSharedPreferences("sharedPrefs" , 0)
val editor = sharedPreferences.edit()
editor.putInt("INT_KEY", mCounter)
editor.commit()
}
private fun loadData() {
val sharedPreferences = getSharedPreferences("sharedPrefs" , 0)
mCounter = sharedPreferences.getInt("INT_KEY", 0)
}
}`
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()
}
}
}
This question already has answers here:
editText get text kotlin
(8 answers)
Closed 4 years ago.
I have been trying to make a simple app in Kotlin using Android Studio, and it looks like there's something wrong with my code. Every time it gets to
var add1 = middle1.toInt()
of the code, the app either crashes or the debugger opens looper.java. I am very new to app development, and I have only ever used Python before this week, so thank you for understanding.
Code:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val getSum = findViewById(R.id.GetSum) as Button
getSum.setOnClickListener {
var addend1 = findViewById(R.id.Addend1) as EditText
var addend2 = findViewById(R.id.Addend2) as EditText
var middle1 = addend1.toString()
var middle2 = addend2.toString()
var add1 = middle1.toInt()
var add2 = middle2.toInt()
var sum = findViewById(R.id.Sum) as TextView
var result = (add1 + add2).toString()
sum.setText(result)
}
}
}
Just modified your code. Try this
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val getSum = findViewById(R.id.GetSum) as Button
val addend1 = findViewById(R.id.Addend1) as EditText
val addend2 = findViewById(R.id.Addend2) as EditText
var sum = findViewById(R.id.Sum) as TextView
getSum.setOnClickListener {
var add1 = addend1.text.toString().toInt()
var add2 = addend2.text.toString().toInt()
var result = (add1 + add2).toString()
sum.setText(result)
}
}
}