How to make calculator over two activities - java

I have made an app where the user selects a food type, enters a weight and then the app calculates the calories. This calorie is then moved onto the MainActivity (when the 'Save' button is pressed) where the total calories will be displayed for that day.
I need the app to take all calories calculated and add them onto any existing values on the main activity. I wrote the code below, however the app crashes when I press the save button my second activity.
String greeting = getIntent().getStringExtra("Greeting Message");
EditText editText1 = (EditText)findViewById(R.id.editText1);
String value = editText1.getText().toString();
Integer aValue = (value != null && !value.isEmpty()) ? Integer.parseInt(value) : 0 ;
Integer bValue = (greeting != null && !greeting.isEmpty()) ? count +=Integer.parseInt(greeting) : 0 ;
editText1.setText(count + "");
Stack Error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nicola.student.mealtracker/com.nicola.student.mealtracker.MainActivity}: java.lang.NumberFormatException: Invalid int: "70.0Cal"

You should check Your value String, Your exception tells me that the String is "70.0Cal". First, You can get a substring, if You know that the last three signs are allways "Cal"
String value = value.substring(0,substring.length()-3);
and second, You have a decimal value, so You should use not integer, You should use Float or double.
also, You should check if the text in the EditText is not null or empty:
String edittextText = editText1.getText().toString();
if(edittextText!=null && !edittextText.equals("")){
//start calculating
}

Either value, or greeting has a value that cannot be converted to int : "70.0Cal".
So remove the suffic "Cal" , and if you have to deal with fractions, use double instead of int.

Looking at the short stack trace provided I can see that you are parsing a String value that is not in a correct Integer format.
You will have to do some validation on the field to make sure that the input provided is a valid numeric value. You can do that by using the following method or by setting the EditText inputType android:inputType="number"
/**
* Checks if the text is a valid numeric value
* #param value
* #return valid
*/
public static boolean isNumeric(String value) {
if (!isNull(value)) {
if (value.matches("[-+]?\\d*\\.?\\d+")) {
return true;
}
}
return false;
}
I would suggest not appending Cal to the value returned. Keep the input numeric. Rather add the "Cal" value in a TextView next to your EditText.
Implement it this way by using the isNumeric method to check the value before parsing.
public void executeYourCode() {
//Parse your values to Double
//as you are using Double values
Double aValue = getCheckedValue(value) ;
Double bValue = getCheckedValue(greeting);
count+= bValue;
editText1.setText(String.valueOf(count));
}
public int getCheckedValue(String value) {
if (value != null && !value.isEmpty() && isNumeric(value)) {
return Double.parseDouble(value.trim());
}
return 0;
}

Related

how add the exception handling after accpeting input in JTextField in java

This is the GUI form that I have created. The value is obtained from the text field and it is stored in the new variable. For some value, it needs to be converted into the integer type. I have converted the value to the integer type, but I am trying to handle the exception when the user doesn't enter any value in the text field. for that, I have used if statement. And for the next exception is when the user enters the string value into the integer field. So I am not been able to handle this exception properly. please help me in doing so.
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if( plat==("") || name==("") || hours==("")|| period==("")|| salary==
("")){
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(ArithmeticException e){
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
First of all you cannot compare Strings like that. Use equals method or isEmpty() to check if String is empty. Second thing is that if String is not parsable to Integer it throws NumberFormatException not an ArithmeticException according to documentation:
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if(plat.isEmpty() || name.isEmpty() || hours.isEmpty() || period.isEmpty()|| salary.isEmpty()) { // changed String comparison
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(NumberFormatExceptione){ // Changed exception type
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
It is never advisable to do like this
plat==("")
do it like this
StringUtils.isEmpty(plat)
and instead of putting integer parsing under try catch you can avoid it with
StringUtils.isNumeric(hours)
and if this condition comes out to false you can take the required action.
Note : StringUtils is available under import apache.commons.lang3

String to Integer from TextField

Stuck on attempting to convert a String to an Integer. I'm using libgdx & I've tried a few mothods of doing it & I keep getting null in return.
Here is my most recent method I've tried also the easiest.
String x = textfield_1.getText();
String y = textfield_2.getText();
Integer integerfield_1 = Integer.getInteger(textfield_1.getText(), null);
if (integerfield_1 == null) {
System.out.println("Incorrect Integer (Integer Only)");
} else {
System.out.println("Please Enter The Position");
//TODO Fill GUI Form.
}
Anyone have any tips?
Take a look at the JavaDocs for Integer.getInteger(String, Integer) for a sec
Returns: the Integer value of the property.
Or in longer terms...
Returns the integer value of the system property with the specified
name. The first argument is treated as the name of a system property.
System properties are accessible through the
System.getProperty(java.lang.String) method. The string value of this
property is then interpreted as an integer value, as per the
Integer.decode method, and an Integer object representing this value
is returned.
If the property value begins with the two ASCII characters 0x or the ASCII character #, not followed by a minus sign, then the rest of
it is parsed as a hexadecimal integer exactly as by the method
valueOf(java.lang.String, int) with radix 16.
If the property value begins with the ASCII character 0 followed by another character, it is parsed as an octal integer exactly as by the
method valueOf(java.lang.String, int) with radix 8.
Otherwise, the property value is parsed as a decimal integer exactly as by the method valueOf(java.lang.String, int) with radix
10.
The second argument is the default value. The default value is
returned if there is no property of the specified name, if the
property does not have the correct numeric format, or if the specified
name is empty or null.
This is not doing what you think it is...
Instead you should be using Integer.parseInt(String), this will throw a NumberFormatException when the value of the String can't be converted to a valid integer...
For example...
String x = textfield_1.getText();
String y = textfield_2.getText();
try {
Integer integerfield_1 = Integer.parseInt(textfield_1.getText());
System.out.println("Please Enter The Position");
//TODO Fill GUI Form.
} catch (NumberFormatException exp) {
exp.printStackTrace();
System.out.println("Incorrect Integer (Integer Only)");
}
If I understand you, then this
Integer integerfield_1 = Integer.getInteger(textfield_1.getText(), null);
Should be something like Integer.parseInt(String) this -
int integerfield_1 = 0;
try {
integerfield_1 = (x != null) ? Integer.parseInt(x.trim()) : 0;
} catch (NumberFormatException e) {
e.printStackTrace();
}
If you really want to use Integer (the wrapper), then you could use Integer.valueOf(String).
Integer integerfield_1 = null;
try {
integerfield_1 = (x != null) ? Integer.valueOf(x.trim()) : null;
} catch (NumberFormatException e) {
e.printStackTrace();
}

Converting a blank input to a zero?

I am using eclipse for an android app and the users input a value that is the used in a formula. When they dont enter the value, it will error out so i want any blank inputs to be changed to zeros. heres the code i have:
EditText numAA=(EditText)findViewById(R.id.numAAAn);
Double num1=Double.parseDouble(numAA.getText().toString());
if ((EditText)findViewById(R.id.numAAAn) == null) {
numAA=0;
}
And it has a error on the 0 that says "type mismatch: cannot convert from int to edittext" so im assuming it wants it converted but im not sure how. I tired adding quotes around the 0 but that didnt work either.
Before parsing the double, check if numAA is empty or null. If it is then assign default value.
This is my solution:
Double num1 = 0.0; // Default value..
EditText numAA = (EditText) findViewById(R.id.numAAAn);
if (numAA.getText() != null && numAA.length() != 0) {
num1 = Double.parseDouble(numAA.getText().toString());
} else {
numAA.setText("0");
}
You can create a separate function to perform this operation. Like:
public Double parseInput(Double defaultValue, EditText editText) {
if (editText.getText() != null && editText.length() != 0) {
return Double.parseDouble(editText.getText().toString());
} else {
editText.setText("0");
}
return defaultValue;
}
And from the caller, use it like:
Double num1 = parseInput(0.0, (EditText) findViewById(R.id.numAAAn));
int counter=0;
EditText numAA=(EditText)findViewById(R.id.numAAAn);
Double num1=Double.parseDouble(numAA.getText().toString());
if ((EditText)findViewById(R.id.numAAAn) == null) {
numAA.setText(counter+"");
}
try this:
Try the following code:
EditText numAA=(EditText)findViewById(R.id.numAAAn);
if (numAA.length()==0) {
numAA.setText("0");//or if you want nothing to show in the edittext, leave this one blank
} else {
Double num1=Double.parseDouble(numAA.getText().toString());
}
}
The length() method checks the length of the string within an edittext.

Get text from textfield

I'm making a GUI program. In my first program I have the following code:
double num1;
num1 = Double.parseDouble(guess.getText());
I believe that this code gets the value from the text field and converts it to double.
How can I get the value and convert it to String or Char?
Since the getText() already returns a String, storing its value as a String is trivial.
In order to parse a double, you've already done it, just watch for the NumberFormatException, in case of invalid input.
To store its value as a char, that depends on your requirements. Do you want the first character? Do you require the string to have only a single character? Is any character valid? And so on.
// Storing the value as a String.
String value = guess.getText();
// Storing the value as a double.
double doubleValue;
try {
doubleValue = Double.parseDouble(value);
} catch (NumberFormatException e) {
// Invalid double String.
}
// Storing the value as a char.
char firstChar = value.length() > 0 ? value.charAt(0) : (char) 0;
// Require the String to have exactly one character.
if (value.length() != 1) {
// Error state.
}
char charValue = value.charAt(0);
use String.valueOf() instead of Double.parseDouble() this will help you convert double into string value
The getText() already returns the text as String.
Btw, be careful of Exceptions due to parse error. But your on the right track. :)
The getText()method returns a String. when you use .parseDouble what you are really doing is turning the string the user entered and into a double therefore in the case of a string you do not have to use a .parse method because the value called is already a string. In the case of a character you would have to use something like this:
String text = jTextField1.getText();
if (text.length() > 1 && !text.contains(" ") && !text.contains(",")) {
//make sure that its length is not over 1, and that it has no spaces and no commas
char ch = text;
} else {
//if a space or comma was found no matter how big the text it will execute the else..
System.out.println("this is not allowed");
jTextField1.setText("");
}
The getText() function already fetches a String value from the Textfield.
For example:
String var = guess.getText();
Here, var is storing the String value received from the Textfield.

how do you call a value entered in a UI to your java class?

Making a simple app for my android.
in my xml interface there is a text box in which the user will input a number (for example: 10). the id of this text box is "input1"
how do I call the value of input1 in java and then perform a calculation on it?
For example...
suppose input1 = x
x + 5 or x*2
and for that matter, how do I have the resulting value appear as constantly updated text output in a specified place on the UI?
In the Activity where you are using this layout XML, you would do this:
private EditText input;
private EditText result;
public void onCreate(Bundle b) {
setContentView(R.layout.my_activity);
// Extract the text fields from the XML layout
input = (EditText) findById(R.id.input1);
result = (EditText) findById(R.id.result);
// Perform calculation when input text changes
input.addKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keycode, KeyEvent keyevent) {
if (keyevent.getAction() == KeyEvent.ACTION_UP) {
doCalculation();
}
return false;
}
});
}
private void doCalculation() {
// Get entered input value
String strValue = input.getText().toString;
// Perform a hard-coded calculation
int result = Integer.parseInt(strValue) * 2;
// Update the UI with the result
result.setText("Result: "+ result);
}
Note that the above includes no error handling: it assumes that you have restricted the input1 text field to allow the input of integer numbers only.
In your XML you can also set android:inputType="number" to only allow numbers as entries.

Categories

Resources