1

i have EditText in my program

my code:

Double Hi;
private EditText MyHight;
MyHight   = (EditText) findViewById(R.id.editText1);

i need to insert to Hi the value on MyHight

i try this:

MyHight.getText().toString();
Hi= (Double)MyHight;

but i got error on casting

how to fix it ?

3 Answers 3

4

Try with:

Hi = Double.valueOf(MyHight.getText().toString());
Sign up to request clarification or add additional context in comments.

Comments

1

You can't cast an EditText to a Double.

You could, however, construct a new Double from the String:

Hi = new Double(MyHight.getText().toString());

or:

Hi = Double.valueOf(MyHight.getText().toString());

Comments

0

Instead of doing something like:

Double Hi = Double.valueOf( (EditText) findViewById(R.id.editText1)).getText().toString())

I used to do the standard casting like the answer by Oli but got tired of handling errors and such. So I wrote a whole class of Casting here is an example of what I did with doubles.

public class Cast {
/**
 *  Base number cast, return the value or default
 * @param object - generic Object
 * @param defaultValue - default value to give if Object is null
 * @return - returns type Number
 */
private static Number castImpl(Object object, Number defaultValue) {
    return (object!=null && object instanceof Number) ? (Number)object : defaultValue;
}


/**
 *  Base double cast, return the value or default
 * @param object - generic Object
 * @param defaultValue - default value to give if Object is null
 * @return - returns type double
 */
public static double cast(Object object, double defaultValue) { 
    return castImpl(object, defaultValue).doubleValue();
}
}

This will allow you use a default value too, here is how yo use it.

Cast.cast("3", 1.0);

I've even done this for Arrays too to convert from int to float arrays...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.