Parsing an integer value in Android - android

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());

Related

GetText compare

So i have a EditText field, which i want to, check if the age is above and under my limits.
if (Integer.parseInt(age.getText().toString()) < 18 && Integer.parseInt(age.getText().toString()) >= 0)
But also, i want to simply check if the field is empty, for what i used.
else if (age.getText().toString().isEmpty())
Unluckly this one is not working, i think it sort of get in to conflict with the first one or something, because i tried with just one condition of both, and it works..
I also tried to store in String variable the method to check isEmpty(), and also in int one, to do the age comparation, but it still not working.
Thanks in advance.
The code should be:
if (age.getText().toString().trim().isEmpty()){
//The EditText field is empty
}else{
try{
if (Integer.parseInt(age.getText().toString().trim()) < 18 && Integer.parseInt(age.getText().toString().trim()) >= 0){
//Your code here
}else{
//Input value is over 18 or under 0
}
}catch(Exception ex){
//There was an error parsing the input (if your user writes letters, parseInt fails)
}
}

Getting Int from EditText causes error?

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));

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");
}
}

string cannot be cast to integer

I am new to using shared preferences and on my first try im getting errors that don't make sense to me. I assign a value like this:
int saveScore = sp.getInt("SAVE_SPOT",0); //This is intentional to get the
//default value of 0 to go to case 0
switch(saveScore){
case 0:
SharedPreferences.Editor edit1 = sp.edit();
edit1.putInt("SCORE_1", score);
edit1.putInt("SAVE_SPOT", 1);
edit1.commit();
break;
case 1:
int previous_score = sp.getInt("SCORE_1",0); // error happens here
if(sp.getInt("SCORE_1",0)>score){
SharedPreferences.Editor edit2 = sp.edit();
edit2.putInt("SCORE_2", score);
edit2.putInt("SAVE_SPOT", 2);
edit2.commit();
}
else{
SharedPreferences.Editor edit3 = sp.edit();
edit3.putInt("SCORE_2", previous_score);
edit3.putInt("SCORE_1", score);
edit3.putInt("SAVE_SPOT", 1);
edit3.commit();
}
break;
Every time i run the program i get the error "string cannot be cast to integer". I am almost 99% sure the variable score is an int and not a string but I am not sure why i am getting this error.
You can check to make 100% it is an int by using 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;
}
If putInt won't work, you could use Integer.parseInt( instead.
I solved my issue, un installing the app is necessary every time in testing because thats the only way to clear the stored data
It seems that with putInt() it won't let you put anything but an int, so that is odd. Are you really telling the full story here?
My guess is that you have ANOTHER key that has the name SCORE_1 that was actually stored as a string, and when you're grabbing out the int, it's picking up the String instead. That's the only way. According to the API:
Throws ClassCastException if there is a preference with this name that is not an int.
So I think SCORE_1 is already in there, and was stored as a string. For the hell of it, try to get out SCORE_1 using getString() instead.
See here: http://developer.android.com/reference/android/content/SharedPreferences.html#getInt%28java.lang.String,%20int%29

Space string issue android

I'm having more and more trouble while trying to make an easy excercise.
i'm trying to delete all eventual starting charater " " in a string.
Example:space-space-space50(i cannot figure it because this forum remove extra space)
result:50
Here's the code ...
char c=textToShow.getText().toString().charAt(1);
int i=1;
while (c == ' '){
textToShow.setText(textToShow.getText().toString().substring(i));
//New char
i++;
c=textToShow.getText().toString().charAt(i);
}
You have the right idea, but your implementaion is off.
First
char c=textToShow.getText().toString().charAt(1);
should start at 0, that is how the indexes are made.
The int is properly initialized but is not even really needed. This is because you work with only the beginning of the String.
However your loop is where things go awry.
Your substring code is proper, but now, you don't need to increment i, since you're modifying the String by shortening it. Also,
c=textToShow.getText().toString().charAt(i);
Should be c=textToShow.getText().toString().charAt(0); You are still checking the beginning of the String.
A more efficient implementation using the loop could be:
char c=textToShow.getText().toString().charAt(0);
String temp = textToShow.setText(textToShow.getText().toString();
while (c == ' ' && temp.length > 0)//also check to see if you're accessing an empty string.
{
temp = temp.substring (1);
c = temp.charAt (0);
}
textToShow.setText (temp);
Of course, this is for an excersice, if you wanted to do it the right way, you'd use temp.trim();

Categories

Resources