20 June 2013

fabian's picture
Posted by fabian on July 19, 2012

So now we want to do actual math with the numbers right? All we need to do is call a method which returns a number. What we need to do is use Integer.valueOf(String string) this will convert the String if it is a number to a number, so if we use Integer.valueOf(text1) + Integer.valueOf(text2) we will be adding two numbers together returning a number, we then want to convert this back into a String to set the Text as so we put this in String.valueOf(int i), this will return the character values of the numbers.

So in the end we want to place this in the setText brackets

String.valueOf(Integer.valueOf(text1) + Integer.valueOf(text2))

This will return the String value of the two numbers added together. Once you put this in the onClick method should look like this

@Override
public void onClick(View v) {
 String text1 = edit1.getText().toString();
 String text2 = edit2.getText().toString();
 textView.setText(String.valueOf(Integer.valueOf(text1) + Integer.valueOf(text2)));
}

Now we should run it and see what happens, remember to save and build.

Now it gives us back a proper math value, you can change what its doing by changing the + sign to something like a multiplication sign.

Plus                
+
Minus
-
Multiply
*
Divide
/

Download Files

So there we go, today we achieved logic. You should now know how to:

  • Get text from a EditText view
  • Set text of a EditText view and TextView
  • Listen for a button click and do something with it
  • Do math
  • Create a string in a programmatic style
  • get the value of a String in numbers
  • Congratulations. If you have gotten this far you are well on your way to being a success.
  • You can download all the examples from here
  • If you have any questions or comments please leave them below, I will be sure to answer.

Thank you for reading through this tutorial.