2011-07-28 5 views
13

EditText에서 이중 값을 가져 와서 다른 Intent로 전달하기 전에 조작합니다. 원시 데이터 형식을 사용하지 않으므로 toString 메서드를 사용할 수 있습니다.Android에서 문자열을 Double로 변환

문제는 내가 protein = Double.valueOf (p) .doubleValue(); 스타일 명령, 프로그램 강제 logcat.If 나는 어떤 코멘트를 남기지 않고 즉시 폐쇄 단백질과 같은 더미 데이터를 설정 = 1.0; 문제없이 작동합니다. 원시 데이터 형식 및 구문 분석 double에서도 같은 결과가 발생합니다. 이 코드는 일반적인 java의 더미 데이터와 완벽하게 작동합니다. 내가 뭘 잘못하고 있니?

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

- gettext에()는 텍스트 뷰가 표시되는 텍스트를 돌려줍니다. http://developer.android.com/reference/android/widget/EditText.html#getText() setText를 다른 버퍼 유형으로 호출하지 않은 경우? – Idistic

답변

2

Double (String) 생성자는 어떻게 사용합니까? 따라서

protein = new Double(p); 

왜 다른지는 모르겠지만 한 번 해보는 것이 좋습니다.

+0

또한 NumberFormatExeption을 여기에 잡는 것이 아니라 문제를 일으킬 수 있습니다. 잡으려고하고 기록하기를 원할 수도 있습니다. – MikeTheReader

+0

왜 NumberFormatException을 잡아 내지 않아도 프로그램을 열지 않고도 강제 종료 할 수 있습니까? – ProfCommie

+0

거기에 어딘가에 NumberFormatException이 생기면 호출 스택을 제어하지 않는 코드로 던져 버릴 것입니다. 특히 사용자 입력을 처리 할 때 그 의미를 아는 곳을 파악하고 처리하는 것이 좋습니다. – MikeTheReader

4

double 개체를 double 값 필드에 할당하는 것처럼 보입니다. 그게 정말 컴파일 되니?

Double.valueOf()는 더블 개체를 생성하므로 .doubleValue()는 필요하지 않습니다. 네이티브 더블 필드를 원하는 경우에

, 당신은 .doubleValue을 더블로 필드를 정의하고 사용할 필요가() 나는 이런 식으로 할 것

+0

예. 컴파일됩니다. 나는 double 대신 double을 사용하므로 intent.putExtra (string, string)를 통해 결과를 다른 활동으로 전달할 수 있습니다. – ProfCommie

+1

@jkj : autoboxing이라고하며 Java의 문서화 된 기능입니다. (편집 : 오히려, 귀하의 의견의 경우 자동 unboxing) – Izkata

56

:

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 
} 

편집 : "프로그램 강제로 logcat에 아무 정보도 남기지 않고 즉시 닫습니다."

logcat 출력에는 정보를 남기지 않고, 일반적으로 강제 종료 ans 거기에 예기치 않은 예외 - 같은 NumberFormatException.

1

나는 비슷한 문제가 있습니다.

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

이 현재 전화 로케일에서 independet하고 올바른 double 값을 반환 : 더블 값으로 올바른 형식의 EditText 텍스트 콘텐츠를이 코드를 사용합니다.

희망이 도움이 되길 바랍니다.

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

귀하의 답변을 형식화하십시오 –

7

이 시도

  • 에서 OnCreate 방법에의 EditText 값을 구문 분석이 원인 응용 프로그램이 중단 될 때 응용 프로그램이 시작될 때 구문 분석 할 값이 없거나 글자 인 자리 표시자가있을 수 있기 때문입니다.

내 코드 : 워드 프로세서

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

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

내가 같은 문제를 가지고,하지만 난 그냥 알아 낸 :

관련 문제