Error in conversion String to Double

0

Hello this is my error and my code.

  

FATAL EXCEPTION: main                     Process: com.idjmatrillegmail.point sales, PID: 7566                     java.lang.NumberFormatException: Invalid double: ""                         at java.lang.StringToReal.invalidReal (StringToReal.java:63)                         at java.lang.StringToReal.parseDouble (StringToReal.java:267)                         at java.lang.Double.parseDouble (Double.java301)                         at java.lang.Double.valueOf (Double.java:338)                         at com.idjmatrillegmail.puntoventa.vista.creaCliente $ 1.onClick (creaCliente.java:61)                         at android.view.View.performClick (View.java:5697)                         at android.widget.TextView.performClick (TextView.java:10826)                         at android.view.View $ PerformClick.run (View.java:22526)                         at android.os.Handler.handleCallback (Handler.java:739)                         at android.os.Handler.dispatchMessage (Handler.java:95)                         at android.os.Looper.loop (Looper.java:158)                         at android.app.ActivityThread.main (ActivityThread.java:7224)                         at java.lang.reflect.Method.invoke (Native Method)                         at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:1230)                         at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)

/////////////////////////////////////////////// ///////////////////////////

THIS IS THE XML

<EditText
                android:id="@+id/txtLimiteCreditoCliente"
                android:layout_width="270dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="4dp"
                android:ems="10"
                android:hint="Limite de Credito"
                android:inputType="numberDecimal"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/txtCelularCliente" />

/////////////////////////////////////////////// ///////////////////////// THIS IS THE CLIENT CLASS

public class Cliente {

    private Integer id;
    private String nombre;
    private String apellidos;
    private String direccion;
    private String sector;
    private String ciudad;
    private String cedula;
    private String telefono;
    private String celular;
    private double limiteCredito;
    private int diasCredito;
    private int usuarioCreador_id;

    public Cliente() {
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Cliente{");
        sb.append("id=").append(id);
        sb.append(", nombre='").append(nombre).append('\'');
        sb.append(", apellidos='").append(apellidos).append('\'');
        sb.append(", direccion='").append(direccion).append('\'');
        sb.append(", sector='").append(sector).append('\'');
        sb.append(", ciudad='").append(ciudad).append('\'');
        sb.append(", cedula='").append(cedula).append('\'');
        sb.append(", telefono='").append(telefono).append('\'');
        sb.append(", celular='").append(celular).append('\'');
        sb.append(", limiteCredito=").append(limiteCredito);
        sb.append(", diasCredito=").append(diasCredito);
        sb.append(", usuarioCreador_id=").append(usuarioCreador_id);
        sb.append('}');
        return sb.toString();
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getApellidos() {
        return apellidos;
    }

    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }

    public String getDireccion() {
        return direccion;
    }

    public void setDireccion(String direccion) {
        this.direccion = direccion;
    }

    public String getSector() {
        return sector;
    }

    public void setSector(String sector) {
        this.sector = sector;
    }

    public String getCiudad() {
        return ciudad;
    }

    public void setCiudad(String ciudad) {
        this.ciudad = ciudad;
    }

    public String getCedula() {
        return cedula;
    }

    public void setCedula(String cedula) {
        this.cedula = cedula;
    }

    public String getTelefono() {
        return telefono;
    }

    public void setTelefono(String telefono) {
        this.telefono = telefono;
    }

    public String getCelular() {
        return celular;
    }

    public void setCelular(String celular) {
        this.celular = celular;
    }

    public double getLimiteCredito() {
        return limiteCredito;
    }

    public void setLimiteCredito(double limiteCredito) {
        this.limiteCredito = limiteCredito;
    }

    public int getDiasCredito() {
        return diasCredito;
    }

    public void setDiasCredito(int diasCredito) {
        this.diasCredito = diasCredito;
    }

    public int getUsuarioCreador_id() {
        return usuarioCreador_id;
    }

    public void setUsuarioCreador_id(int usuarioCreador_id) {
        this.usuarioCreador_id = usuarioCreador_id;
    }

    public Cliente(String nombre, String apellidos, String direccion, String sector, String ciudad, String cedula, String telefono, String celular, double limiteCredito, int diasCredito, int usuarioCreador_id) {

        this.nombre = nombre;
        this.apellidos = apellidos;
        this.direccion = direccion;
        this.sector = sector;
        this.ciudad = ciudad;
        this.cedula = cedula;
        this.telefono = telefono;
        this.celular = celular;
        this.limiteCredito = limiteCredito;
        this.diasCredito = diasCredito;
        this.usuarioCreador_id = usuarioCreador_id;
    }
}

/////////////////////////////////////////////// /////////////////

Here I try to pass the value

cliente.setLimiteCredito(Double.valueOf(limiteCredito.getText().toString()));
    
asked by Ivan De Js Matrille 14.11.2018 в 05:18
source

2 answers

0

Since the value of your class is double (primitive), you have to use a method that returns a compatible type. When you use the valueOf method it returns a Double (wrapper, wrapper in English) that is not the same as double (primitive).

In this case the appropriate method would be parseDouble , which is defined as follows:

public static double parseDouble(String s)
                          throws NumberFormatException
     

Returns to new double initialized to the value represented by the   specified String, as performed by the valueOf method of class Double.

     

Parameters: s - the string to be parsed.

     

Returns: the% co_of% value represented by the string argument.

     

Throws:    double - if the string is null

     

NullPointerException - if the string does not contain a parsable   double.

In effect, this method receives a string and returns a NumberFormatException (primitive), which is what you need. Therefore, this is how it should work:

cliente.setLimiteCredito(Double.parseDouble(limiteCredito.getText().toString()));

Before doing this, you should verify or control the exceptions that the method can generate: double , which can occur if the value you take is not convertible to NumberFormatException and double that happens if the value written is null. In those cases, if you do not control the error, you will have a crash in your code.

You can do it like this:

try{
    /*
       *Aquí usamos un ternario para asignar 0 cuando la cadena sea nula
       *así despejamos el NPE
    */
    String txt = limiteCredito.getText().toString() != null ? limiteCredito.getText().toString() : "0";

    double lCredito=Double.parseDouble(txt);
    cliente.setLimiteCredito(lCredito);

}catch(NumberFormatException ex){ 
   //manejar la excepción mostrando el error o enviando 0.00 a la clase...
}

That way, if the user types NullPointerException in the text box or leaves it blank, the app will not crash. Although it is always convenient to apply restrictions on data entries. For example, in a xyz that will collect a TextView , not allow undue data to be written or left blank.

    
answered by 14.11.2018 в 05:51
0

The problem is caused by trying to convert a variable that contains an empty string ("") to Double :

  

java.lang.NumberFormatException: Invalid double: ""

As you point out the error occurs in this line since the value of limiteCredito.getText().toString() is "" :

cliente.setLimiteCredito(Double.valueOf(limiteCredito.getText().toString()));

for this you can perform a method to return a default value in case the value in EditText can not be converted to Double :

public static Double evaluaDouble(String number){
    Double resultado = 0.0; //Valor default si no es numerico.
    try{
        if(number != null){
            resultado = Double.valueOf(number);
        }
    }catch(NumberFormatException nfe){
        Log.w("Error", "NFException value: " + number);
    }
    return resultado;
}

and you call the method this way:

cliente.setLimiteCredito(evaluaDouble(limiteCredito.getText().toString()));
    
answered by 14.11.2018 в 06:19