Robert Robert - 3 months ago 30
Android Question

How to use EditText value (numberDecimal) in math operations Java

I have a EditText view :

<EditText
android:id="@+id/vorgabezeit"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="#0277BD"
android:imeOptions="actionDone"
android:inputType="numberDecimal"
android:maxLength="5"
android:textAlignment="textEnd"
android:textColor="#ffffff"
android:textCursorDrawable="@null"
android:textStyle="bold"
/>


The value entered in this EditText I would like to use it in an math operation.
Before I had fixed values :

public void submitOrder(View view) {
displayPrice((procente / myEditNum) * mitarbeiter);
}


where variables were defined as :

int procente = 120;
int mitarbeiter = 1;


Now, I searched for hours on the web how to take that value entered in EditText and use id further, and this is as close as I got :

public class MainActivity extends AppCompatActivity {
int procente = 120;
int mitarbeiter = 1;
EditText myEdit = (EditText) findViewById(R.id.vorgabezeit);
String myEditValue = myEdit.getText().toString();
double myEditNum = Double.parseDouble(myEditValue);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void submitOrder(View view) {
displayPrice((procente / myEditNum) * mitarbeiter);
}
}


The application crashes from the start.
Thank you for your patience and help.

Best regards,
Robert

Answer

Make sure you add android:inputType="number" to your EditText on the xml to ensure the user can ONLY type numbers on it, then :

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.button)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        displayPrice((procente / Double.parseDouble(((EditText) findViewById(R.id.vorgabezeit))
                                .getText().toString())) * mitarbeiter);
                    }
                });
    }

btw your code crashes because you called findviewById before setting the content view to the activity so basically it searches on a non-existing layout and your edit text and button become null because of it

Comments