Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Getting Double from String

Building a simple app which pulls data from edittext boxes, performs calculation and outputs an answer.

trying to pull data as edit text, then convert to string, then to double. Seems like there should be a more direct way, but this seems like it should technically work.

public class MainPage extends Activity {
    private EditText mbalanceEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
        mbalanceEditText = (EditText)findViewById(R.id.balanceEditText);
        String bal = mbalanceEditText.getText().toString();
        Double mbalDouble = Double.parseDouble(bal);

When I run, I receive a fatal error:
Caused by: java.lang.NumberFormatException: Invalid double: "" at java.lang.StringToReal.invalidReal(StringToReal.java:63) at java.lang.StringToReal.parseDouble(StringToReal.java:248) at java.lang.Double.parseDouble(Double.java:295)

Is it a syntax error, or something else? Also, is there a more convenient way to do this?

1 Answer

Hello,

Right now, you are trying to get the data value from the EditText right when you start your Activity. It looks like you are getting a default value of the empty string which parseDouble is throwing an Exception on since it isn't a number. More likely, what you would want to do is have a button that you push and then get the string and parse it after the button is pressed. If you need more assistance please let us know and we can provide further assistance.