2011-07-28 13 views
13

Intentando obtener valores dobles de un EditText y manipularlos antes de pasarlos a otro Intent. No uso el tipo de datos primitivo para poder usar los métodos de String.Conversión de String a Double en Android

El problema es cuando incluyo la proteína = Double.valueOf (p) .doubleValue(); comandos de estilo, la fuerza del programa se cierra inmediatamente sin dejar información en el logcat. Si los comulgo y configuro algunos datos ficticios como protein = 1.0; funciona sin problemas Lo mismo sucede con los tipos de datos primitivos y el análisis doble. Este código funciona perfectamente con datos ficticios en java normal. ¿Qué estoy haciendo mal?

EditText txtProt, txtCarb, txtFat, txtFiber, txtPoints; 
String p, c, f, fi; 
Double protein, carbs, fat, fiber; 
double temp; 
Integer points; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Log.v("Create Prompt", "ready for layout"); 
    setContentView(R.layout.main); 
    Log.v("Layout Created", "ready for variable assignment"); 
    txtProt = (EditText) findViewById(R.id.Protein); 
    txtCarb = (EditText) findViewById(R.id.Carbs); 
    txtFat = (EditText) findViewById(R.id.Fat); 
    txtFiber = (EditText) findViewById(R.id.Fiber); 
    txtPoints = (EditText) findViewById(R.id.Points); 
    btnCalc = (Button) findViewById(R.id.Calc); 
    Log.v("Variables Assigned", "ready for double assignment"); 

    p = txtProt.getText().toString(); 
    c = txtCarb.getText().toString(); 
    f = txtFat.getText().toString(); 
    fi = txtFiber.getText().toString(); 


    protein=Double.valueOf(p).doubleValue(); 
    carbs=Double.valueOf(c).doubleValue(); 
    fat=Double.valueOf(f).doubleValue(); 
    fiber=Double.valueOf(fi).doubleValue(); 
    Log.v("Doubles parsed", "ready for calculations"); 
    //these are the problem statements 

    protein = 1.0; 
    carbs = 1.0; 
    fat = 1.0; 
    fiber = 1.0; 

    protein *= 16; 
    carbs *= 19; 
    fat *= 45; 
    fiber *= 14; 

    temp = protein + carbs + fat - fiber; 
    temp = temp/175; 

    points = new Integer((int) temp); 
+0

A partir de los documentos - getText() Devuelve el texto del TextView está mostrando. http://developer.android.com/reference/android/widget/EditText.html#getText() a menos que hayas llamado a setText con un tipo de buffer diferente? – Idistic

Respuesta

2

¿Qué ocurre con el uso del constructor Double (String)? Por lo tanto,

protein = new Double(p); 

No sé por qué sería diferente, pero podría valer la pena intentarlo.

+0

Además, no está detectando NumberFormatExeption en ningún lugar, podría estar causando su problema. Puede que desee capturar y registrar eso, también, por las dudas. – MikeTheReader

+0

¿por qué no atrapar una NumberFormatException hace que el programa se cierre forzosamente sin siquiera abrirse? – ProfCommie

+0

Si obtiene una excepción NumberFormatException en algún lugar, se lanzará a la pila de llamadas, en un código que no controla. Es mejor atraparlo y manejarlo donde sepas lo que significa, especialmente cuando se trata de la entrada del usuario. – MikeTheReader

4

Parece que asigna Objeto doble en doble Campo de valor. ¿Eso realmente compila?

Double.valueOf() crea un objeto Double por lo que .doubleValue() no debería ser necesario.

Si desea nativa campo doble, es necesario definir el campo como doble y luego usar .doubleValue()

+0

Sí compila. Estoy usando Double en lugar de Double para poder pasar los resultados a otra actividad a través de un intent.putExtra (string, string). – ProfCommie

+1

@jkj: Se llama autoboxing y es una característica documentada de Java. (EDITAR: más bien, auto-unboxing en el caso de su comentario) – Izkata

56

lo haría de esta manera:

try { 
    txtProt = (EditText) findViewById(R.id.Protein); // Same 
    p = txtProt.getText().toString(); // Same 
    protein = Double.parseDouble(p); // Make use of autoboxing. It's also easier to read. 
} catch (NumberFormatException e) { 
    // p did not contain a valid double 
} 

EDIT: "la fuerza del programa se cierra inmediatamente sin dejar información en el logcat"

No sé si no dejo información en la salida del logcat, sino que generalmente me cierra la fuerza ans hay una excepción no detectada, como NumberFormatException.

1

Tengo un problema similar. para el formato de texto de contenido correcto EditarTexto al valor doble utilizo este código:

try { 
     String eAm = etAmount.getText().toString(); 
     DecimalFormat dF = new DecimalFormat("0.00"); 
     Number num = dF.parse(eAm); 
     mPayContext.amount = num.doubleValue(); 
    } catch (Exception e) { 
     mPayContext.amount = 0.0d; 
    } 

esto es independet de teléfono local actual y regresar doble valor correcto.

espero que sea de ayuda;

-2
String sc1="0.0"; 
Double s1=Double.parseDouble(sc1.toString()); 
+1

por favor formatee su respuesta –

7

intente esto:

double d= Double.parseDouble(yourString); 
1
kw=(EditText)findViewById(R.id.kw); 
    btn=(Button)findViewById(R.id.btn); 
    cost=(TextView)findViewById(R.id.cost); 


      btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { cst = Double.valueOf(kw.getText().toString()); 
      cst = cst*0.551; 
      cost.setText(cst.toString()); 
     } 
    }); 
1

que tenían el mismo problema, pero sólo he dado cuenta de que:

  • analizar el valor EditarTexto en el método OnCreate causó la la aplicación se cuelga porque cuando se inicia la aplicación, no hay valores para analizar o quizás los marcadores de posición que son letras.

Mi código:

package com.example.herodav.volumeapp; 

import android.renderscript.Double2; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.*; 
import android.widget.*; 

import org.w3c.dom.Text; 

public class MainActivity extends AppCompatActivity { 

    EditText height, length, depth; 
    TextView volume; 
    double h,l,d,vol; 


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

     height = (EditText)findViewById(R.id.h); 
     length = (EditText)findViewById(R.id.l); 
     depth = (EditText)findViewById(R.id.d); 
     volume = (TextView)findViewById(R.id.v); 

     Button btn = (Button)findViewById(R.id.btn); 
     btn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       calculateVolume(); 
       volume.setText("Volume = " + String.valueOf(vol)); 
      } 
     }); 
    } 

    public void calculateVolume(){ 
     h = Double.parseDouble(height.getText().toString()); 
     l = Double.parseDouble(length.getText().toString()); 
     d = Double.parseDouble(depth.getText().toString()); 
     vol = h*l*d; 
    } 
} 

I

Cuestiones relacionadas