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");
}
}
Related
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));
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
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
I am trying to get integer value entered in EditText by user.
EditText eTextValue=(EditText) findViewById(R.id.eId);
String eTextString=eTextValue.getText().toString();
int eTextValue1=Integer.parseInt(eTextString);
But unluckily I am getting,
unable to parse 9827328 as integer.
I have tried using Integer.valueOf instead of Integer.parseInt but again I am getting the same exception.
I have even used Long datatype to store value instead of int type datatype but nothing seems to be working.Any help over this will be highly appreciated.
I have gone through all these links unable to parse ' ' as integer in android , Parsing value from EditText...but nothing seems to be working all of them are landing me in exception.
You are using eTextValue as a variable name for two different things (an int and an EditText). You cant do that and expect it to work properly. Change one or the other and it should work better.
Try by entering the following in the XML File under the corresponding EditText element.
android:inputType="number"
Hope this should get you pass the exception.
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(eTextString)
int eTextValue1=Integer.parseInt(eTextString);
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps
int id;
id=Integer.parseInt(ed.getText().toString());
I am trying to parse a double from an edittext but i keep getting a number format exception error.
i initially tried this...
premiumvalue = Double.parseDouble(premium.getText().toString());
amountweightvalue = Double.parseDouble(amountweight.getText().toString());
Then attempted this...to no avail.
try{
premiumvalue = Double.parseDouble(premium.getText().toString());
} catch (final NumberFormatException e) {
premiumvalue = 0;
}
try{
amountweightvalue = Double.parseDouble(amountweight.getText().toString());
} catch (final NumberFormatException e) {
premiumvalue = 0;
}
I'm a noob and any help fixing this would be greatly appreciated.
I have test your code test your code myself and find the following possibility to find NumberFormatException:
if EditText value is blank, So apply condition for EditText blank value.
if EditText value is only dot(.), So apply condition for EditText dot value.
in your comment you are saying that you are using this
String text = premium.getText().toString();
if(text.equals(".")||text.equals("-.")||text.equals(""))
{
premium.setText("0");
}
so my point is that
are you using same thing for both premium and amountweight EditText and then parse string to double??
and why you need to check condition for '_' because if you set android:inputType="numberDecimal" attribute for EditText then EditText only accept 0-9 and . value.
you don't need to trim EditText value bacuse Edittext do not accept blank space if you are using android:inputType="numberDecimal" attribute.
don't need to check null condition because EditText never return null value.
I have test your code lot of way and do not find NumberFormatException if i follow above points.