Question

all.

I'm meeting a problem to which no solution I found, worked, so I humbly ask for any help you may give me.

I'm building an android app with the following code. Everything works fine, except for one small detail. If I leave the textField empty I'll get an error when parsing the value.

I couldn't implement most of the solutions I found online, so below I present the code to see if anyone may be of assistance on this particular case.

package com.hitbyatruck.delaycalc;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

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

    public void calculateClickHandler(View view){

        if (view.getId() == R.id.calculate_button) {
            EditText temp1 = (EditText) findViewById(R.id.temp_input);
        EditText dist1 = (EditText) findViewById(R.id.dist_input);
        TextView result1 = (TextView) findViewById(R.id.result);

        if (dist1 == null | temp1 == null){
            result1.setText("Please, provide some input.");
        }
        else {
            double temp = Double.parseDouble(temp1.getText().toString());
            double dist = Double.parseDouble(dist1.getText().toString());

            if(dist == 0){

                result1.setText("Your delay should be set to 0                               miliseconds.");    
            }

            else{
                int delay_ms = calculate(temp, dist);

                result1.setText("Your delay should be set to about " + Integer.toString(delay_ms) + " miliseconds.");
            }       
        }
    }
}

private int calculate(double temp, double dist) {
    return (int) ((dist / (331.45 + (0.597 * temp))) * 1000);
}

}

I appreciate any help you may give me. The code above was the first working code I wrote before discovering the parsing error, but the null condition check didn't work out.

I tried several other methods, but either wasn't able to implement them on my code or it simply just didn't do the job.

Thanks in advance for any attention given to my question.

All the best.

Was it helpful?

Solution

You are getting a NULL Pointer when trying to parse an empty string value (you can't parse the empty NULL value).

Try this:

String doubleString = dist1.getText().toString();

if (doubleString.equals("")) {
   // Do something here (maybe assign a default) to your double or something
} else {
   double dist = Double.parseDouble(doubleString);
}

OTHER TIPS

You could write a method like this:

private boolean isEmpty(TextView text){
    return text !=null && !text.getText().toString().isEmpty();
}

So basically, check both the view itself and its value

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top