patternjavaMinor
Using Java to Add the Contents of two EditText views in Android
Viewed 0 times
theedittextandroidcontentsjavaviewstwousingadd
Problem
I have a toy app that contains:
I know:
This code is working for simple cases.
Is there a more direct way of reading the values and performing the addition?
editText1for entering a number. UsesinputTypeofnumber.
editText2for entering a second number. UsesinputTypeofnumber.
adderButtonfor triggering addition.
textVeiwfor displaying the result of the addition.
I know:
- The naming could be better
- I should check for overflow/underflow on the addition and elsewhere.
This code is working for simple cases.
public void adder_click(View view) {
EditText et1 = (EditText) findViewById(R.id.editText1);
EditText et2 = (EditText) findViewById(R.id.editText2);
Integer s = Integer.valueOf(et1.getText().toString()) + Integer.valueOf(et2.getText().toString());
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(s.toString());
}Is there a more direct way of reading the values and performing the addition?
Solution
That code is a bit dangerous.
As for simplifying the method, it is not good that you call
Remember that you should probably wrap the code in a try catch block unless you can guarantee the text field will only contain decimal numbers. Also, add in your overflow/underflow logic as well.
Integer.valueOf() can throw NumberFormatException which you make no effort to catch. This will happen if you have commas in numbers or non-digit characters. Your other comments are also very important.As for simplifying the method, it is not good that you call
findViewById 3 times every time you press a button. I would store references to editText1, editText2 and textView externally (of this method), as then you can reuse all three here and elsewhere in your code with subtract/multiply etc. You can then remove three lines of code and just have:Integer s = Integer.valueOf(et1.getText().toString()) + Integer.valueOf(et2.getText().toString());
tv.setText(s.toString());Remember that you should probably wrap the code in a try catch block unless you can guarantee the text field will only contain decimal numbers. Also, add in your overflow/underflow logic as well.
Code Snippets
Integer s = Integer.valueOf(et1.getText().toString()) + Integer.valueOf(et2.getText().toString());
tv.setText(s.toString());Context
StackExchange Code Review Q#60601, answer score: 6
Revisions (0)
No revisions yet.