Android NumberFormatException error with a simple number input from EditText - android

So I have a simple Edit-text with number input.
User enters his phone number and it is saved into DB obviously that is the goal.
now every time i do
int contactNumber=Integer.parseInt(mContactNumber.getText().toString());
I get an error thrown saying NumberFormatException for some reason it doesn't like a string of number. I have made sure that mContactNumber field in the android input field has the
android:input="number"
now i also tried just to be sure
int contactNumber=Integer.parseInt(mContactNumber.getText().toString().trim());
still the same error
Guys any ideas?

Try putting the Type to ' long ' instead of ' int '. Hope that will work for you.

This might be because you are leaving the text field empty. Are you sure you are not parsing an empty string?

You need to put a simple condition:
if(mContactNumber.getText().length()>0)
{
int contactNumber=Integer.parseInt(mContactNumber.getText().toString().trim());
}

For phone Number you can not take it as Integer. try to take it as string only and after getting that string you can do the check for the numbers only by
TextUtils.isDigitsOnly(str);

Related

Number Format Exception "Invalid Double"

I have to build a calculator and i am making some validations, the code is kinda long so i will only put the part that is breaking it.
It is a validation that makes the multiplication, it breaks when trying to multiply a negative number, every other operation is done correctly but the multiplication:
else if(resulttxt.getText().toString().contains("*")){
String resultarray=resulttxt.getText().toString();
String[] split=resultarray.split("\\*");
finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
resulttxt.setText(String.valueOf(finalresult));
resulttxt is received from a TextView that gets it's data from cliking on the numbers or the signs which are also TextViews (not buttons but they do have the On click listener)the operation is done when ciclking on the = sign.
This throws an error if for example i try to do -6*45:
java.lang.NumberFormatException: Invalid double: "6*45"
Like i said everything works with the addition,substraction and division it is only the multiplication that breaks.
I tried executing your code in the compiler :
String resulttxt = "-6*45";
boolean negative = false;
if(resulttxt.contains("*")){
String resultarray=resulttxt;
String[] split=resultarray.split("\\*");
double finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
System.out.println(finalresult);
}
Every thing worked fine for, please verify datatype used in your program.
addition, multiplication and division works fine. "-6+45, -6*45 and -6/45"(any other combination. I just used the same)
However for subtraction as the pattern is "-6-45" the above logic will fail and throw number format exception. This is because if you split "\-", the "-" is first character in string and there is nothing before it.
Thus your split will fail. So to avoid this you can always take last index of character to split using substring function.
OMG dudes... this is what was the problem:
I had this validation at the end of the other operations, so BEFORE even going to the multiplication part it entered the "-" validation when it checks
if(resulttxt.contains("-")){
because it is a negative value so it does have a "-"... so it entered as a substraction instead as a multiplication because of that...
To solve it i had to put the substraction validation at the bottom of all of them.
So thank you for the guys who suggested me to check the line where the error was thrown i wouldn't have known logcat actually tells you were the mistake is and to my surprise it was on the substraction validation which to me was a "WTF" moment and then i realized what i just told you.
Try this instead :
String s1 = resultarray.substring(0,resultarray.indexOf("*"));
String s2 = resultarray.substring(resultarray.indexOf("*")+1,resultarray.length());
double d1= Double.valueOf(s1);
double d2= Double.valueOf(s2);
Hope this helps

Calculator final output issue

I am creating a calculator app in android. It should calculate anonymously whatever is on textBox. For e.g. I enter 1+2.5-5*8 in textBox. But when I call addition method the app gets crashed. Because the input is in string format and answer I want is in numeric format. I used string buffer. I tried in java that when I enter (1+1+3-1) in stringBuffer and I display using println() method it give correct answer but same does not happen with string buffer when I take that value from editText.
You have to convert string into integer or float.
Use Integer.parseInt("") method to covert to integer and Float.parseFloat("") to convert to float.
First of all welcome to StackOverFlow
It might help if you add code and the error log in the question
So I am gonna cover all the possible things that might be happening wrong in your program:
NumberFormatException- you might not be converting the string "12" into int 12 to do so use Interger.parseInt(your string buffer with number only here);
Try using a stack and a queue for your solution (google it you will get details)
You might be making a mistake in getting string from edittext it sometimes give NullPointerException
if above is not enough comment and add your code asap

Run time errors in eclipse android application [unfortunately application has stopped]

I am facing an issue in my app ,when I click the button inside my app it gives the error
(unfortunately application has stopped),
and these are problems in Logcat :
please help me out ,what exactly is the issue ?
i solved it , thnx guys
You have an editText which accepts inputs other than numbers also.
I assume you are trying to convert the value in the editText to an Integer using
Integer.parseInt ((String) EditText.getText());
Either restrict the input in the editText to numbers only.
Or, Handle Number format Exception gracefully with an appropriate error message!
It looks like you're trying to parse a value starting "android.widget.EditText" - which suggests you may have code like this:
int x = Integer.parseInt(editText.toString());
That's not going to get the text of the EditText - for that, you want to call getText():
int x = Integer.parseInt(editText.getText().toString());

Android: buffer.toString() dosen't work

I trying to connect my Android application to a database on remote host.
I want to use the records of the DB, but there's a problem when i try to do this:
if(buffer.toString()=="OPEN")
{
button_signal.setText("OPEN");
}
else
{
button_signal.setText("CLOSE");
}
I have checked buffer.toString() using Logs, and it is equal to "OPEN", but the button_signal's text is printed "CLOSE". Why? Can you help me?
It might have some invisible characters or some letters might be in different case, so please try this:
buffer.toString().trim().equalsIgnoreCase("OPEN");
You can't compare String with the "==" Operator in Java. A String is an Object.
Try this buffer.toString().equals("OPEN");
EDIT:
Even better is if you compare it like this: "OPEN".equals(buffer.toString())
Because it won't throw an exception if buffer is null.

Why does this trigger a force close on Android?

Why does this code trigger a force close in Android?
`score.setText(Integer.parseInt((String) score.getText())+1);`
score is a TextView, and I am simply increasing the number by 1. I have predefined a String resource to be the initial number in the score TextView.
I am quite frustrated.
First off you should try breaking down your code so you can actually see what is going on with it.
Instead of
score.setText(Integer.parseInt((String) score.getText())+1);
try
String tmp = score.getText().toString();
int score;
score = Integer.parseInt(tmp) + 1;
score.setText(String.valueOf(score));
EDIT: Upon further reading of the documentation, setText has several overloads, one of which DOES take an int, but it takes the int of a resource ID. My guess is that your score is not a valid resource ID, thus crashing your application.
public final void setText (int resid)
Oh and as far as the frequent FC's when beginning Android Dev, it happens to the best of us. The key is to learn WHY the FC's happen, and have a LOT of patience.
mostly u need to do this
score.setText(Integer.parseInt(score.getText().toString())+1);
coz.. getText() returns a Editable Object which cannot be parsed to Integer. So it give NumberFormat Exception.
AndMake sure to set TextView,s Text to an integer initially..
try this way
score.setText(String.valueOf(Integer.parseInt(score.getText().toString())+1));
as you can pass the integer value that's why getting force the application
TextEdit.setText takes a CharSequence as input.
You are supplying an integer through Integer.parseInt((String) score.getText())+1
See, if converting it back to string and using it in setText helps.
You can convert an integer to string using Integer.toString.
PS: I am new to java myself.
The compiler should have ideally caught this error.
It's possible java uses some implicit type conversions from string to int.

Categories

Resources