开发者

Problem with casting in java for android

开发者 https://www.devze.com 2023-04-04 10:49 出处:网络
i have EditText in my program开发者_开发技巧 my code: Double Hi; private EditText MyHight; MyHight= (EditText) findViewById(R.id.editText1);

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 ?


Try with:

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


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());


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号