Getting Int from EditText causes error? - android

So first of all sorry if this has already been asked and answered before, I couldn't find anything relating to my issue.
So I'm working on a project for college and I need to get int values from EditText widgets. I was told to use parseInt to do this however when running my program, that line of code causes the application to crash. I don't know what I'm doing wrong, I'm still very new to android development, thanks for the help :)
public void Calculate (View view)
{
int MilesTravelled;
int FuelUsed;
int MPG;
/* the two lines below are what cause the application to crash */
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
FuelUsed = (int) (FuelUsed / 4.55);
MPG = MilesTravelled / FuelUsed;
lblMPG.setText(FuelUsed);
}

Do you have this in the onCreate() function?
EditText txtMilesTravelled = (EditText) findViewById(R.id.YourEditText);
But I think you mixed Integer and int. They are not the same:
See this link!

First of all, don't capitalize the first letter of an variables or method names. Following the Java coding conventions, only do that for classes.
What is probably causing your app to crash is you trying to set the text of a label to an integer. The setText method for a TextView needs to take in a string.
So change:
lblMPG.setText(FuelUsed);
to:
lblMPG.setText(String.valueOf(FuelUsed));
Otherwise it might be that it's trying to parse a non-numerical string to an integer.
For exmaple, if the EditText is blank, it will cause your app to crash. To prevent that, try this:
int MilesTravelled = 0, FuelUsed = 0;
try {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(), "Error NFE!", 0).show();
nfe.printStackTrace();
}
This way, it will catch a NumberFormatException error (parsing a string to an integer that can't be represented as an integer, such as "hello"). If it catches the error, it will toast that an error has occurred and your integer variables will remain 0.
Or you could just test if the strings contain only digits using the following regex:
int MilesTravelled = 0, FuelUsed = 0;
if (txtMilesTravelled.getText().toString().matches("[0-9]+")) {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
} else {
// contains characters that are not digits
}
if (txtFuelUsed.getText().toString().matches("[0-9]+")) {
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} else {
// contains characters that are not digits
}
If that's not the problem, then make sure you define your variables properly.
txtMilesTravelled and txtFuelUsed should be EditText:
EditText txtMilesTravelled = (EditText)findViewById(R.id.txtMilesTravelled);
EditText txtFuelUsed = (EditText)findViewById(R.id.txtFuelUsed);
And make sure that your R.id.editText actually exists on your layout and that the IDs are the correct ones.
Last thing, make sure FuelUsed is not 0 before calculating MPG because then you are dividing by 0:
int MPG = 0;
if (FuelUsed != 0) {
MPG = MilesTravelled / FuelUsed;
}

I am assuming that you're entering perfect integers in the EditTexts. It might be a good idea to use the trim function txtMilesTravelled.getText().toString().trim() before using parseInt.
However, I think the major problem is here : lblMPG.setText(FuelUsed);
FuelUsed is an integral value, when you pass an integer to setText(), it looks for a string resource with that integral value. So you should be passing a String to the setText() method.
Use : lblMPG.setText(Integer.toString(FuelUsed));

Related

How do I set the text of an EditText to an Int?

In an attempt to set an EditText to an Int value, I've tried various ways of converting the Int to a value that the EditText will accept, but all fail:
processButton.setOnClickListener {
var intNo = inputText.text as Int
intNo *= 2
outputText.text = intNo as String // error = "required editable"
outputText.text = intNo.toString() // err: type mismatch
outputText.text = Int.toString(intNo) // type mismatch reqd editable
outputText.text = "What is going on?" // type mismatch reqd editable
}
How can I set the EditText to an Int value?
var a: Int = 12
var s: String = a.toString()
This should work for this.
Try given code it will work. What I am doing here I am converting inputText first to String then Int. After I am multiplying with 2 then I am assigning a value for outputText by converting to string.
processButton.setOnClickListener {
var intNo = inputText.text.toString().toInt()
intNo *= 2
//println(intNo.toString())
val myString = intNo.toString()
// If you using outputText as Editable then use this
outputText.text = SpannableStringBuilder(myString)
}
There are a couple things going on here, and to understand them, let's take a look at the various getText and setText methods that EditText has:
Editable getText()
void setText(CharSequence text)
void setText(#StringRes int resid)
// many other setText methods with buffer options
So what Kotlin does here to let you use property syntax is that it creates a text property. The getter used for the property is obvious, since there's only one. The setter for the property is supposed to be the one that takes a CharSequence parameter (it would make sense, Editable extends CharSequence), but actually trying to assign anything other than an Editable to it won't work. See this issue.
To get to the problem at hand, you can read the value in your EditText and convert it to a String like this:
val input = inputText.text.toString()
Then, you can use the toInt() function from the standard library to convert it to an Int (be aware that this will throw an exception if the String can't be parsed):
val doubled = input.toInt() * 2
And finally, you can set the value of the EditText by calling the setText setter in the traditional Java style, passing in a String:
inputText.text.setText(doubled.toString())
A bit of a mess because of the two-way conversion between String and Int, plus the oddities of how the text property is generated here, but that's the way to do it. If you're bothered by how this looks, you could always hide some of this mechanism behind extension properties.
var num: Int = 5
to convert to string would be
num.toString()

Get EditTextValue and parse it into a decimal with only one digit for integer part

I'm having an issue when I get a whole number from an EditText and try to change that to a decimal so I can use it for calculations. Could someone explain how to do this?
For Example. if someone was to enter 120 into the EditText and I got the integer from it, how would I then change that integer of 120 into 1.20 and continue calculations with it?
Thanks!!
EditText myEditText = (EditText)findViewById(R.id.YOUR_EDIT_TEXT_ID);
String numberAsString = myEditText.getText().toString();
double myDecimal;
try {
myDecimal = Double.parseDouble(numberAsString);
if (myDecimal >= 10)
{
int digits = 1 + (int)Math.floor(Math.log10(myDecimal));
myDecimal = myDecimal / ((Math.pow((double)10, ((double)digits) - 1)));
System.out.println(myDecimal);
}
} catch (NumberFormatException e) {
//handle exeption
e.printStackTrace();
}
You need to get the contents from your EditText as a string, and from there you can parse it into an integer. This is done like so:
int wholeNum = Integer.parseInt(yourEditText.getText().toString());
int three = Integer.parse("3");
I know you can use this to parse a string into an integer, there is probably a parse method in double aswell!
Check this also :
Convert a String to Double - Java
+1 to anthony for answering 1 minute before me haha

Determine if content in editText is a "." ONLY

I have written a calculator type app. My mates found that entering single decimal points only into the editText's makes the app crash. Decimal numbers and integers work fine, but I get a number format exception when .'s are entered.
I want to check if a single . has been placed in an editText, in order for me to display a toast telling the user to stop trying to crash the app.
My issue is that a . doesn't have a numerical value...
You can wrap it in a try/catch which should be done anyway when parsing text. So something like
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
This way it will protect against any number format exception and will make the code more reusable later on.
You can treat .1 as 0.1 by the following.
String text = et.getText().toString();
int len = text.length();
// Do noting if edit text just contains a "." without numbers
if(len==0 || (len==1 && text.charAt(0).equals(".")))
return;
if(text.charAt(0).equals(".") && text.length() > 1) {
text = "0" + text;
}
// Do your parsing and calculations

Compare R.id to int

I am building an simple Android app am looking for a way to compare number input to a pre-stored integer. My first though was:
if(R.id.number == 123456){
}
This comparison does not work. I have also tried .equals, with no avail. Does anyone have any thoughts on how to compare the two values?
The R.id.number refers to a View's id (most likely an EditText since you say you are comparing user input). Thus, comparing that to a number would definitely not be what you're looking for. Find the EditText via findViewById(), parse its text into an integer and compare that.
Eg
public void onCreate (Bundle b){
super.onCreate (b);
EditText e = (EditText) findViewById (R.id.number);
int num = 0;
try{
num = Integer.parseInt (e.getText().toString().trim());
}
catch (NumberFormatException e){
}
if (num == 123456){
System.out.println ("Input equal");
}
}

Add a number and a Text Input value with adobe flex

I am trying to add a number and a text input value to display in a label. here is my code thus far.
'lblAnswer.text = bloodglucose + 100;'
Please tell me what I am doing wrong.
Please try following answer -
bloodglucose += 100;
lblAnswer.text = String(bloodglucose);
Hope this will work :)
Sunil is correct - when doing mixed type addition, the UI input first needs to be coerced to either int or Number. IE: Number(bloodglucose) + 100; This assumes bloodglucose is actually a getter to the input text reference. If it's not, then you need to coerce the property and not the id of the component.
Getter: public function get bloodglucose():Number { return Number(myInput.text); }
In method: lblAnswer.text = bloodglucose + 100;
or (bloodglucose is a UIComponent):
In method: lblAnswer.text = Number(bloodglucose.text) + 100;
You should use String(int i)
lblAnswer.text = String(bloodglucose + 100);
Update: What about something like this:
var i:int = bloodglucose + 100;
var s:String = String(i);
lblAnswer.text = s;
** Update ,
I am changing the code from the update that was previously posted. I initially found that because I was including the string value inside of the equation this is what was prompting an error. You have to wrap the converted components to Number inside of the string all together. Basically convert the components to a number, then convert the answer received into a string.
Below is an example of the wrong code.
txtAnswer = (String(Number(bloodglucose)+100)) / 36)).toFixed(2)
Below this line is the fixed code.
txtAnswer.text = String( (Number(bloodglucose.text) + (Number(100))/ (Number(36))).toFixed(2) ;
The .toFixed Property signifies how many decimal places I want the returned value to display.

Categories

Resources