Giogiosw
Giogiosw

Reputation: 11

Get Number From Edit text, won't add up?

I am not able to get sum of the two numbers entered in a pair of EditText fields. The EditTexts are set to take numeric input.

Java :

EditText x1 = (EditText)findViewById(R.id.Tensione);
EditText x2 = (EditText)findViewById(R.id.Potenza);
String x3;
x3 = x1 + x2;

activity.xml:

EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/Tensione"
    android:layout_below="@+id/Testo_Calcolo1"
    android:layout_centerHorizontal="true"
    android:editable="false"
    android:numeric="integer|signed|decimal" /

EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="numberPassword|number|numberDecimal|numberSigned"
    android:ems="10"
    android:id="@+id/Potenza"
    android:layout_below="@+id/textView8Testo_Calcolo"
    android:layout_alignParentStart="false"
    android:layout_centerHorizontal="true"
    android:numeric="integer|signed|decimal" />

Error:

Error:(51, 21) operator + cannot be applied to android.widget.EditText,android.widget.EditText

Upvotes: 0

Views: 315

Answers (1)

indivisible
indivisible

Reputation: 5012

Your issue is that an EditText is not a number or even a String. It is a View that has a String contained in it.

EditText x1 = (EditText)findViewById(R.id.Tensione);
EditText x2 = (EditText)findViewById(R.id.Potenza);
...

// get the Strings from the EditTexts
String x1Contents = x1.getText().toString();
String x2Contents = x2.getText().toString();

// convert Strings to ints
int x1Number = Integer.parseInt(x1Contents);
int x2Number = Integer.parseInt(x2Contents);

// then add them together
int x3Number = x1Number + x2Number;

This is not a complete solution. You will still need to grab the contents when you know the EditTexts have values and make sure that it is numeric input or ensure you handle non-numeric input appropriately.

Upvotes: 4

Related Questions