This question already has answers here:
Edit Text shows exception Invalid Int ""
(5 answers)
Closed 6 years ago.
I am getting java.lang.NumberFormatException: Invalid int: error
I believe the declarations are appropriate
I have taken input of numbers in string earlier itself.
The below part only calculates the sum.
Second part is a continuation of 1st part.
Declaration is given below:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num1 = (EditText)findViewById(R.id.num1);
final EditText num2 = (EditText)findViewById(R.id.num2);
final EditText resu = (EditText)findViewById(R.id.resu);
resu.setFocusableInTouchMode(false);
resu.setFocusable(false);
resu.setClickable(false);
final Button plus = (Button)findViewById(R.id.plus);
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
On click program:
plus.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View view) {
try{
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
}catch(Exception e){
resu.setText(""+e);
}
}
);
Move the following code inside your onlick() method, because in your oncreate() if the EditText is empty it will return empty String (""), so you need to get the value when the button is clicked, not before it:
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
To:
plus.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
try {
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
} catch(Exception e) {
resu.setText(""+e);
}
}
});
Problem lies on Integer Object to float primitive type conversion. I think if you give an input a Whole Number then your code should work fine. code
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
But if it's not a whole Number then inorder to incounter NumberFormatException you're failing to convert String into your appropriate primitive Data type.
And also check for empty String ("") in n1 and n2 by if(n1=="")
plus.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
try
{
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
if(n1==""){
n1="0";
}
float sum = Float.valueOf(n1) + Float.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
}
catch(Exception e)
{
resu.setText(""+e);
}
}
});
Related
This question already has answers here:
How to parse a double from EditText to TextView? (Android)
(9 answers)
Closed 6 years ago.
First time into Java and I'm trying to create a simple tips calculator for my coworkers at the restaurant I work for, but when I leave one of the editText fields empty the program crashes.
MainACtivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalTipsInput = (EditText) findViewById(R.id.totalTipsInput);
waiter1Hours = (EditText) findViewById(R.id.waiter1Hours);
waiter2Hours = (EditText) findViewById(R.id.waiter2Hours);
waiter3Hours = (EditText) findViewById(R.id.waiter3Hours);
waiter4Hours = (EditText) findViewById(R.id.waiter4Hours);
tipsPerHourView = (TextView) findViewById(R.id.tipsPerHourView);
totalHoursView = (TextView) findViewById(R.id.totalHoursView);
barsCutView = (TextView) findViewById(R.id.barsCutView);
waiter1Pay = (TextView) findViewById(R.id.waiter1Pay);
waiter2Pay = (TextView) findViewById(R.id.waiter2Pay);
waiter3Pay = (TextView) findViewById(R.id.waiter3Pay);
waiter4Pay = (TextView) findViewById(R.id.waiter4Pay);
taxDepositView = (TextView) findViewById(R.id.taxDepositView);
Button calcBtn = (Button) findViewById(R.id.calcBtn);
calcBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
double cWaiter1Hours = Double.parseDouble(waiter1Hours.getText().toString());
double cWaiter2Hours = Double.parseDouble(waiter2Hours.getText().toString());
double cWaiter3Hours = Double.parseDouble(waiter3Hours.getText().toString());
double cWaiter4Hours = Double.parseDouble(waiter4Hours.getText().toString());
double resultTotalHours = cWaiter1Hours + cWaiter2Hours + cWaiter3Hours + cWaiter4Hours;
double resultBarsCut = (totalTips * 7) / 100;
double resultTaxDeposit = resultTotalHours * 3;
double resultTipsPerHour = (totalTips - resultBarsCut - resultTaxDeposit) / resultTotalHours;
double resultWaiter1Pay = cWaiter1Hours * resultTipsPerHour;
double resultWaiter2Pay = cWaiter2Hours * resultTipsPerHour;
double resultWaiter3Pay = cWaiter3Hours * resultTipsPerHour;
double resultWaiter4Pay = cWaiter4Hours * resultTipsPerHour;
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(resultTipsPerHour));
barsCutView.setText(Double.toString(resultBarsCut));
waiter1Pay.setText(Double.toString(resultWaiter1Pay));
waiter2Pay.setText(Double.toString(resultWaiter2Pay));
waiter3Pay.setText(Double.toString(resultWaiter3Pay));
waiter4Pay.setText(Double.toString(resultWaiter4Pay));
taxDepositView.setText(Double.toString(resultTaxDeposit));
}
});
}
Tried to do something like this but got an error with .length():
if (double totalTips = Double.parseDouble(totalTipsInput.getText().toString()).length() < 1 || totalTipsInput = null) {
totalTips = 0
} else {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
}
Use this method in your class:
public static Double returnDouble(EditText editText)
{
try {
if(editText.getText().toString().isEmpty())
{
return 0d;
}
else
{
return Double.parseDouble(editText.getText().toString());
}
} catch (NumberFormatException e) {
return 0d;
}
}
You can do something like this to make sure that the input to the "parseDouble" is valid:
double totalTips = 0;
Editable totalString = totalTipsInput.getText();
if(totalString.length() > 0){
totalTips = Double.parseDouble(totalString.toString());
}
If the "totalTips" field can take user input you need to make sure they can only enter a valid number. The lazy way might be to put a try/catch around the parseDouble as well, and handle the case where someone may enter something that can't be parsed to a double (ie, empty string, letters, malformed numerical value)
I would recommend not trusting users to always input valid values in the rest of the waiter hours fields as well. You would want to do similar checks on those fields before attempting to parse the input.
If (loanAmtValue!=null) is used..it throws an error ie."Operator != cannot be applied to float,null". Plzz sum1 come up with a solution to this prob.. The app crashes if no value is given in that field. So I was trying to use null condition check so that app doesn't crash even if no value is given.
public class SICalculatorActivity extends Activity implements View.OnClickListener {
private Button submit;
private Button submit2;
SeekBar sb;
TextView yrs;
EditText loanAmt;
EditText roi;
TextView siResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
final int years;
sb = (SeekBar)findViewById(R.id.set_years);
yrs = (TextView)findViewById(R.id.years);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
yrs.setText(sb.getProgress()+" year(s)");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
addButtonClickListener();
}
private void addButtonClickListener() {
submit = (Button)findViewById(R.id.button);
submit.setOnClickListener(this);
submit2 = (Button)findViewById(R.id.button2);
submit2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
float loanAmtValue = 0;
float roiValue = 0;
double answer=0;
float y = sb.getProgress();
loanAmt = (EditText)findViewById(R.id.amt);
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
roi = (EditText)findViewById(R.id.roi);
roiValue = Float.parseFloat(roi.getText().toString());
if (loanAmtValue != null && roiValue != null){
case R.id.button:
answer = (loanAmtValue * roiValue * y) / 100;
siResult = (TextView) findViewById(R.id.result);
siResult.setText("Simple Interest for Amount Rs." + loanAmtValue + " and ROI " + roiValue + "% for "+y+" year(s) is = " + String.format("%.2f", answer));
loanAmt.setText("0");
roi.setText("0");
break;
}
}
else
{
siResult.setText("Please provide valid details");
}
}
}
float is a primitive data type and not an object. null check is used for objects.
For primitives you should use the default values check. For float the default value is 0.0f.
Read following:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
http://www.c4learn.com/java/java-default-values/
It looks like your problem is here :
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
This line will throw NumberFormatException if loanAmt doesn't contain a String that can be converted to a float.
You can check that the String is not empty before attempting to convert to float :
if (loanAmt.getText() != null && !loanAmt.getText().isEmpty()) {
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
}
This would still throw an exception if the user enters an invalid String, so you'll have to catch the exception :
if (loanAmt.getText() != null && !loanAmt.getText().isEmpty()) {
try {
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
catch (NumberFormatException ex) {
loanAmtValue = 0.0; // or some other default value
}
}
Null is used for objects. If an object is null, then this means this variable points to nowhere.
Obj a = null // a points nowhere
a = new Obj() // now a points to a place in the memory (a references an Obj object in the memory
And float is not an object type, it's a primitive type. But be carefull if you make comparison like: x == 0.0 (float comparison is not like comparison integers!).
To complete the answers, You cannot check if a float is null, like everybody said here. What You can do is, like "Der Golem" said check it if it is !=0, if You want to get sure that the value is not 0 (not the same like null!!!). BUT:
To prevent a NumberFormatException You also have to be sure, that Your catched value from the edit text field is a number. You can do it with TextUtils:
android.text.TextUtils.isDigitsOnly(CharSequence str).
In Your case, You should do it like this:
loanAmt = (EditText)findViewById(R.id.amt);
String loanAmtString = loanAmt.getText().toString();
if(android.text.TextUtils.isDigitsOnly(loanAmtString)){
loanAmtValue = Float.parseFloat(loanAmtString);
}
roi = (EditText)findViewById(R.id.roi);
String roiString = roi.getText().toString();
if(android.text.TextUtils.isDigitsOnly(roiString)){
roiValue = Float.parseFloat(roiString);
}
In my opinion, there are two ways to enforce user to enter only float values.
Using inputType for EditText
Checking entered text by a regular expression
Pattern ptrn = Pattern.compile("^\\d*\\.\\d*$");
String enteredText = ...;
if(ptrn.matcher(enteredText).matches()){
// try to parse the string here
}
i'm using a NumberTextWatcher for realtime-edit for an EditText and it's working fine for me,
but some users reporting that they got NumberException problem, i think this is because numbers changes in 123,456 in EditText and cant parse to doubles, so i did some change and use Replace("," , "") code but this is not working for some too!
what should i do so this code works for all of my users?
Thanks and Sorry for my Poor English :D
NumberTextWatcher:
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
And Here is MainActivity:
final EditText amount = (EditText) findViewById(R.id.editText1);
final EditText duration = (EditText) findViewById(R.id.editText2);
final EditText interest = (EditText) findViewById(R.id.editText3);
amount.addTextChangedListener(new NumberTextWatcher(amount));
duration.addTextChangedListener(new NumberTextWatcher(duration));
interest.addTextChangedListener(new NumberTextWatcher(interest));
String amount1 = amount.getText().toString().replaceAll(",", "");
String duration1 = duration.getText().toString().replaceAll(",", "");
String interest1 = interest.getText().toString().replaceAll(",", "");
try{
double i = Double.parseDouble(amount1);
double j = Double.parseDouble(duration1);
double z = Double.parseDouble(interest1);
}
catch(NumberFormatException e){
}
Programs store and operate on numbers in a locale-independent way. Before displaying or printing a number, a program must convert it to a String that is in a locale-sensitive format. For example, in France the number 123456.78 should be formatted as 123 456,78, and in Germany it should appear as 123.456,78. So you can't just replace "," and ".".
The following code is an example on how to convert from double and back using the current currency of a user in the United States.
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Currency;
import java.util.Locale;
public class Test
{
public static void main(String[] args)
{
Locale currentLocale = Locale.getDefault();
Currency currentCurrency = Currency.getInstance(currentLocale);
Double currencyAmount = new Double(9876543.21);
NumberFormat currencyFormatter =
NumberFormat.getCurrencyInstance(currentLocale);
System.out.println(NumberFormat.getNumberInstance(currentLocale));
System.out.println(
currentLocale.getDisplayName() + ", " +
currentCurrency.getDisplayName() + ": " +
currencyFormatter.format(currencyAmount));
try
{
System.out.println(currencyFormatter.parseObject("$9,876,543.21"));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What else could you do:
* make sure users are entering properly formatted numbers. For example, you should not see any other chars except numbers , . + - $, etc.
* IF you know the user will ALWAYS enter two decimal digits, for example, 10 dollars would be expressed as 10.00 (or 10,00), then you can safely remove all "," and "." and get the original number by dividing it by 100, but remember to also remove spaces (remember France :) )
Also, check the documentation: http://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html
The problem is probably that other users might be inputting ill-formatted numbers. So you are just replacing the commas with white spaces. Maybe you should replace all non-digit characters?
amount1 = amount.getText().toString().replaceAll("[^\\d]", "");
Or if you want them to leave the decimal points then use the following:
amount1 = amount.getText().toString().replaceAll("[^\\d.]", "");
i'm trying to do this feature where i calculate the calories needed in BMIcalculation class, then i created another class called CalorieIntake where in here i'll calculate the total calorie intake. (i do this by extends the BMIcalculation class.)
Then when i click on the 'Check' button, it should compare between this two value and show the interpretation. However i keep getting error at the 'interpretDiff(float diffValue)' part it mentioned it must return with a String value.
Here are my codes..pls help me to check where to problem is. Or is there a better way to do so? pls advice me. Thanks a lot..
public class CalorieIntake extends BMIcalculation {
TextView counter1;
Button compare;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.form_calorieintake2);
Button btn_calcIntake = (Button) findViewById(R.id.button_calcIntake);
btn_calcIntake.setOnClickListener(btnListener_calcIntake);
counter1 = (TextView) findViewById(R.id.textView_totalCalorieIntake);
Button compare = (Button) this.findViewById(R.id.checkIntake);
compare.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try {
if ((!counter1.equals("")) && (!caloriesresult.equals("")))
{
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
}
}catch (Exception k)
{ System.out.println(k);
Toast.makeText(CalorieIntake.this, "Error", Toast.LENGTH_SHORT).show();
}
}
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
{
return "Eat more";
}
}
private float calDiff(float calorieIntake, float calorieNeed) {
return (float) (calorieIntake - calorieNeed);
}
});
}
In interpretDiff, what happens if diffValue is not less than 100? You return nothing. However, java requires that you return something, as that is what the declaration of the method implies.
A solution would be:
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
return "Eat more";
return "Eat less";
}
The else statement for if diffValue is not less than 100 is not necessary here because the second return statement is only called if diffValue >= 100 (since hitting a return statement exits out of the method).
With regards to the issue of the exception being thrown, and the Toast error being called, that can only happen as a result of the following code:
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
Assuming findViewById doesn't have an issue in it, the error is probably coming from getting the text of counter1E, caloriesresultE (if they are null). If neither of those are null, then check to make sure callDiff and interpretDiff don't have bugs in them. Finally, make sure compareText is not null.
I made a program that computes the geometric mean and my program is already working but i have some sort of errors. Whenever i click the btnCalculate with an empty input in my inputValues my program stops working. how am I going to deal with this error? Thanks:)
final AutoCompleteTextView inputValues = (AutoCompleteTextView) findViewById(R.id.txt_input);
final TextView txtTotalNum = (TextView) findViewById(R.id.txt_totalNumber);
final TextView GeoMean= (TextView) findViewById(R.id.txt_GeoMean);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
});
Button btnclear = (Button)findViewById(R.id.btnclear);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
inputValues.setText("");
txtTotalNum.setText("");
GeoMean.setText("");
}
You are getting errors because your code is trying to split on empty strings or null and then accessing values[] that really have no index at all. Just check if the string fetched by the EditText has a length>0.
#Override
public void onClick(View agr0) {
String fetchedValues = ( inputValues.getText().toString());
if(fetchedValues.length>0)
{
String []values = fetchedValues.split(",");
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
else
{
//alert the user that the field is empty
}
}
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
if(values !=NULL){
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
// try this
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
if(inputValues.getText().toString().length()>0){
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
});
Your program stops at
convertedValues[a] =Integer.parseInt(values[a]);
because for an empty input the split array has no values, so its length is 0. And when you try to access values[0]you get an ArrayIndexOutOfBoundsException.
Just check if the input is emty, before splitting it.
if(!inputValues.getText().toString().equals("")){
... // do your stuff
} else {
// show a message
}