[Android]Error during parseInt() - android

Writing my first android app. Almost everything works except this function. Even when all the text boxes have some numeric value, the app crashes in this function. Also, is there a better way to retrieve all the values in these text boxes and convert it to int. Note that all the textboxes are input type number on the activity.xml file.
public int updateclks()
{
try{
EditText v1= (EditText) findViewById(R.id.editText1);
EditText v2 = (EditText) findViewById(R.id.EditText01);
EditText v3 = (EditText) findViewById(R.id.EditText02);
EditText v4 = (EditText) findViewById(R.id.EditText03);
EditText c1= (EditText) findViewById(R.id.EditText04);
EditText c2 = (EditText) findViewById(R.id.EditText05);
EditText c3 = (EditText) findViewById(R.id.EditText06);
EditText c4 = (EditText) findViewById(R.id.EditText07);
try{ //error occurs somewhere around this block
vsel[1]= Integer.parseInt(v1.getText().toString());
vsel[2]= Integer.parseInt(v2.getText().toString());
vsel[3]= Integer.parseInt(v3.getText().toString());
vsel[4]= Integer.parseInt(v4.getText().toString());
clk[1]= Integer.parseInt(c1.getText().toString());
clk[2]= Integer.parseInt(c2.getText().toString());
clk[3]= Integer.parseInt(c3.getText().toString());
clk[4]= Integer.parseInt(c4.getText().toString());
}
catch(NumberFormatException e)
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Fields cannot be empty", duration);
toast.show();
return 1;
}
return 0;
}

parseInt() is not crashing your app.Because if any exception occurs for this parseInt it will be caught as you handled it.Since your application is still crashing see vse1 and clk1 array whether you created these correctly or not.
Also notice about array length if you created vse1 array of length 4.Then You may want to start with index 0 rather than 1.Otherwise ArrayIndexOutOfBounds will crash your application.

I also got the same problem and u can solve it by using trim function.
clk[1]= Integer.parseInt(c1.getText().toString().trim());

Related

Android AlertDialog input as an Integer

I have an AlertDialog where the user needs to type a number between 1-24 and I stor that for later use. Now to store the number input as an integer I do this:
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
String test = userInput.getText().toString();
int testNumber;
try {testNumber = Integer.parseInt(test); }
catch (NumberFormatException e) { testNumber = 0;}
Now when testing it seems that whatever number I use as input in the dialog window, it always returns 0, even if it was just a normal number. What can I do that I don't get a NumberFormatException?
EDIT:
After further testing I found that whatever I give as input on my emulator, I always get an empty string.
testNumber = Integer.parseInt(test.trim());
Replace with this, it will be fixed.
.trim() removes extra spaces.

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

Big number calculating in Android without Exponent "E"

I am using Double data type for a variable in my Android app.
It simply takes a number and shows whatever percentage increase from that number would be:
for example 1,000,000 plus 1000 % = 1.1E7
The problem is I don't want an exponent display (the E), I want it to be in decimal.
This is a code snippet of the area which when the user clicks a Calculate button the info is displayed in an editText (Textbox)
enter code here
Button calc2 = (Button)findViewById(R.id.button1);
calc2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
EditText number1 = (EditText)findViewById(R.id.editText1);
EditText number2 = (EditText)findViewById(R.id.editText2);
EditText number3 = (EditText)findViewById(R.id.editText3);
double editText1 = Double.parseDouble(number1.getText().toString());
double Pluspercent = Double.parseDouble(number2.getText().toString());
double editText3 = Double.parseDouble(number3.getText().toString());
double Result1 = 0 ;
double Result2 = 0;
Result1 = Pluspercent * 0.01 ;
Result2 = editText1 * Result1;
editText3 = editText1 + Result2 ;
number3.setText(editText3 + "");
}
});
enter code here
The code works but displays with the E. Could you show me what code to use to simply get it to display the result as in decimal. The decimal result should be 11,000,000
No need to worry about commas at the moment.
Some languages use a Decimal data type which would take care of this problem I think. Anyone know why Android do not have this?
I looked at
http://lecturesnippets.com/android-variables-data-types/
which shows a list of the data types, but Double seems to be the biggest container and uses the Exponent thing I don't want.
Thanks for any help.
Al
You're looking for a DecimalFormat object. You want to pass your double into the DecimalFormat.format( ... ) method to get a StringBuffer, and then append the rest of the text you'd like to display to that StringBuffer before you pass it to your EditText.
You'll be particularly interested in this method:
public StringBuffer format (double value, StringBuffer buffer, FieldPosition position)

How to get the last input only in EditText? (Android)

For example, if user types "abc" in the EditText field, I just want to get the last character "c".
String last = yourEditText.getText().toString();
last = last.substring(last.length() - 1);
System.out.println("last character: " + last);
Expanding DonGru's post, with another alternative of getting the last character
EditText et;
et = (EditText) findViewById(R.id.et);
CharSequence s = et.getText();
System.out.println(s.subSequence(s.length()-1, s.length()));
since getText() returns a CharSequence you can also use that for getting the last character:
EditText my;
my = (EditText) findViewById(R.id.editText1);
CharSequence myCharSeq = my.getText();
System.out.println(myCharSeq.charAt(myCharSeq.length() - 1));

Removing space from Edit Text String

In my android app, I am getting the String from an Edit Text and using it as a parameter to call a web service and fetch JSON data.
Now, the method I use for getting the String value from Edit Text is like this :
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
Now normally it works fine, but if we the text in Edit Text contains space then my app crashes.
for eg. - if someone types "food" in the Edit Text Box, then it's OK
but if somebody types "Indian food" it crashes.
How to remove spaces and get just the String ?
Isn't that just Java?
String k = edittext.getText().toString().replace(" ", "");
try this...
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
String newData = k.replaceAll(" ", "%20");
and use "newData"
String email=recEmail.getText().toString().trim();
String password=recPassword.getText().toString().trim();
In the future, I highly recommend checking the Java String methods in the API. It's a lifeline to getting the most out of your Java environment.
You can easily remove all white spaces using something like this. But you'll face another serious problem if you just do that. For example if you have input
String input1 = "aa bb cc"; // output aabbcc
String input2 = "a abbcc"; // output aabbcc
String input3 = "aabb cc"; // output aabbcc
One solution will be to fix your application to accept white spaces in input string or use some other literal to replace the white spaces. If you are using only alphanumeric values you do something like this
String input1 = "aa bb cc"; // aa_bb_cc
String input2 = "a abbcc"; //a_abbcc
String input3 = "aabb cc"; //aabb_cc
And after all if you are don' caring about the loose of information you can use any approach you want.

Categories

Resources