axu
axu

Reputation: 53

Getting a decimal number from EditText on Android Studio

EDIT:Solved!

I know this has been posted before, but the answers I've seen from those are not working for me.

I'm trying to get the input from one textfield (which i've specified as a decimal input) but can't think of any other way to get the value of it other than to toString it.

What I have below crashes and the error logs say

java.lang.IllegalStateException: Could not execute method of the activity

public void buttonOnClick(View v){
    // do something when the button is clicked

    Double inputNum;

    TextView mField = (TextView) findViewById(R.id.mField);
    TextView kmField = (TextView) findViewById(R.id.kmField);

    if(mField.length() > 0){
        inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
        mField.setText(inputNum.toString());
    }
}

Upvotes: 3

Views: 5945

Answers (2)

Amarjit
Amarjit

Reputation: 4357

java.lang.IllegalStateException: Could not execute method of the activity

Possible reason that this issue occur is kmField.getText().toString() return null. So please put some validation over here for kmField

public void buttonOnClick(View v){
    // do something when the button is clicked

    Double inputNum;

    TextView mField = (TextView) findViewById(R.id.mField);
    TextView kmField = (TextView) findViewById(R.id.kmField);

    if(kmField.getText().toString().isEmpty()){
        inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
        mField.setText(inputNum.toString());
    }
}

Upvotes: 3

Archit Goel
Archit Goel

Reputation: 704

xml file:

<EditText
           android:id="@+id/editS0"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:ems="10"
           android:hint="@string/S0"
           android:inputType="numberDecimal" />
<Button
           android:id="@+id/getS0"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@string/setS0" />

in your java file:

EditText textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);

btn_S0.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v)
    {
       double S0 = Double.parseDouble(textS0.getText().toString());
    }
});

Upvotes: 1

Related Questions