I am doing some calculation but unable to parse a string into int or even in float.I searched for solution and i read it somewhere there must be a empty string but i checked my
put these lines inside onClick()
final String height = e1.getText().toString();
final int a = Integer.parseInt(height);
You are fetching value of e1
in onCreate()
, while you want it when user click on button
Also need to check whether height is having any value or not, check Stuluske's answer for this
You are trying to parse an empty String ( "" ) to a numerical value, but "" is not a numerical value.
Make sure you set it to required, or check for emptiness before trying to parse it.
final int a = !height.equals("")?Integer.parseInt(height) : 0;
for instance.
EDIT:
If you have added spaces, so it would be " ";
height = height.trim();
final int a = !height.equals("")?Integer.parseInt(height) : 0;
should do the trick.
you should get the values inside a method so that your app does not try to assign the values immediatly you are creating them check below how am doing it using kotlin
myresult = findViewById<TextView>(R.id.txtresult)
val1 = findViewById<EditText>(R.id.valone)
val2 = findViewById<EditText>(R.id.valtwo)
after getting the field use method as below
fun calculate() : Int {
var value1 = Integer.parseInt(val1.text.toString())
var value2 = val2.text.toString().toInt()
var result : Int
when (opType){
"+" ->{result = value1 + value2
return result
}
"-" ->{result = value1 - value2
return result
}
"*" -> {result = value1 * value2
return result
}
"/" -> {result = value1 / value2
return result
} else -> result = 20
}
return result
}
btn.setOnClickListener{
println(calculate().toString())
myresult.text = calculate().toString()
}
for those moving to kotlin and finding the same error I hope this code will help you
put a check before doing Integer.parseInt like
final int a = (height == null || height.trim().equal("") ? 0 : Integer.parseInt(height));
Also you need to add this code for getting the height value from edittext inside onclick listener as when in OnCreate control will not have any value apart you set some default value in layout.xml as it is just created
There's no value yet when onCreate()
runs. Move the getText()
and parseInt()
inside your click listener to read and parse the value when you have entered something.