[android] Converting String to Double in Android

Trying to get double values from an EditText and manipulate them before passing them to another Intent. Not using primitive data type so I can use toString methods.

Problem is when I include the protein=Double.valueOf(p).doubleValue(); style commands, the program force closes immediately without leaving any info in the logcat.If I comment them out and set some dummy data like protein = 1.0; it works with no problems. Same happens with primitive data types and parse double. This code works perfectly with dummy data in normal java. What am I doing wrong?

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

This question is related to android string double android-edittext

The answer is


I would do it this way:

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: "the program force closes immediately without leaving any info in the logcat"

I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.


i have a similar problem. for correct formatting EditText text content to double value i use this code:

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;
    }

this is independet from current phone locale and return correct double value.

hope it's help;


You seem to assign Double object into native double value field. Does that really compile?

Double.valueOf() creates a Double object so .doubleValue() should not be necessary.

If you want native double field, you need to define the field as double and then use .doubleValue()


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

I had the same issue, but I have just figured out that :

  • parsing the EditText value in the Oncreate method caused the app to crash because when the app starts, there are no values to parse or maybe the placeholders which are letter.

My code:

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


try this:

double d= Double.parseDouble(yourString);

What about using the Double(String) constructor? So,

protein = new Double(p);

Don't know why it would be different, but might be worth a shot.


String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to double

Round up double to 2 decimal places Convert double to float in Java Float and double datatype in Java Rounding a double value to x number of decimal places in swift How to round a Double to the nearest Int in swift? Swift double to string How to get the Power of some Integer in Swift language? Difference between int and double How to cast the size_t to double or int C++ How to get absolute value from double - c-language

Examples related to android-edittext

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Design Android EditText to show error message as described by google Change EditText hint color when using TextInputLayout How to change the floating label color of TextInputLayout The specified child already has a parent. You must call removeView() on the child's parent first (Android) Edittext change border color with shape.xml Changing EditText bottom line color with appcompat v7 Soft keyboard open and close listener in an activity in Android EditText underline below text property Custom designing EditText