2013-11-01 3 views
-1

저는 Java에 익숙하지 않고 현재 일부 예제를 수정 한 다음 내 자신의 응용 프로그램을 만들어 Java에 대한 열세를 보이고 있습니다. 그러나 나는 앱을 드러내려고 할 때이 오류가 계속 발생합니다. 코딩 사이트에서 오류가 발생하지 않았습니다. 누구든지 이걸보고 오류가 어디 있는지 말해 줄 수 있습니까? 난 단지 당신이 말할 수있는,불행히도 (앱)이 중지되었습니다.

package com.example.caloriescalculator; 

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

public class BMIcalculation extends Activity 
{ 
EditText weightE = (EditText)findViewById(R.id.weightText); 
EditText heightE = (EditText)findViewById(R.id.heightText); 
EditText ageE = (EditText)findViewById(R.id.ageText); 
EditText caloriesresult = (EditText)findViewById(R.id.caloriesText); 
RadioButton male = (RadioButton) findViewById(R.id.maleradio); 
RadioButton female = (RadioButton) findViewById(R.id.femaleradio); 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.bmilayout_main);  
    Button calories = (Button) findViewById(R.id.caloriesButton); 
    calories.setOnClickListener(new OnClickListener() 
     { 
     @Override 
       public void onClick(View arg0) 
       {  
        int weight = 0, age = 0, height = 0, caloriesneed = 0; 
        String weightE, heightE, ageE; 
        weightE = getString(R.id.weightText); 
        heightE = getString(R.id.heightText); 
        ageE = getString(R.id.ageText); 

           if (weightE != "" && heightE != "" && ageE != "") 
           { 

            if (male.isSelected()) 
             { 
              caloriesneed = (int) (655 + 9.6*weight + 1.8*height - 4.7*age); 
              caloriesresult.setText(caloriesneed); 
             } 

            else if (female.isSelected()) 
             { 
              caloriesneed = (int) Math.round (66 + 13.7*weight + 5*height - 6.8*age); 
              caloriesresult.setText(caloriesneed); 
             } 
           } 

       } 
     }); 
} 

public void calculateClickHandler(View view) 
{ 
    // make sure we handle the click of the calculator button 

if (view.getId() == R.id.calculateButton) 
{   
    // get the references to the widgets 
    EditText weightText = (EditText)findViewById(R.id.weightText); 
    EditText heightText = (EditText)findViewById(R.id.heightText); 
    TextView resultText = (TextView)findViewById(R.id.resultLabel); 

    // get the users values from the widget references 

    float weight = Float.parseFloat(weightText.getText().toString()); 
    float height = Float.parseFloat(heightText.getText().toString()); 

    // calculate the BMI value 

    float bmiValue = calBMI(weight, height); 

    // interpret the category based on the BMI value 
    String bmiInterpretation = interpretBMI(bmiValue); 

    // now set the value in the result text 

    resultText.setText("Your current BMI :" + bmiValue + " - " + bmiInterpretation); 
} 
} 

    // the formula to calculate the BMI index 
    // check for http://en.wikipedia.org/wiki/Body_mass_index 
    private float calBMI (float weight, float height) { 

    return (float) (weight *10000/(height * height)); 
    } 
    // interpret what BMI means 
    private String interpretBMI(float bmiValue) 
    { 

    if (bmiValue < 16) 
    { 
    return "Severely underweight"; 
    } else if (bmiValue < 18.5) { 

    return "Underweight"; 
    } else if (bmiValue < 25) { 

    return "Normal"; 
    } else if (bmiValue < 30) { 

    return "Overweight"; 
    } else { 
    return "Obese"; 
    } 

    }      

} 로그 캣 오류없이

+2

stacktrace를 게시하십시오. –

+0

코드에서 Java, AFAICT가 아니라 Android를 배우려고합니다. * Java! = Android *. – SudoRahul

+0

안드로이드는 developer.android.com에서 배우기 시작해야합니다. –

답변

1

이동 onCreate

EditText weightE ; 
EditText heightE ; 
EditText ageE ; 
EditText caloriesresult; 
RadioButton male ; 
RadioButton female; 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
super.onCreate(savedInstanceState); 
setContentView(R.layout.bmilayout_main); // must be first 
weightE = (EditText)findViewById(R.id.weightText); // then initialize your views 
heightE = (EditText)findViewById(R.id.heightText); 
ageE = (EditText)findViewById(R.id.ageText); 
caloriesresult = (EditText)findViewById(R.id.caloriesText); 
male = (RadioButton) findViewById(R.id.maleradio); 
female = (RadioButton) findViewById(R.id.femaleradio); 
...// rest of the code 

findViewById 내부의 모든 초기화는 현재 팽창 레이아웃 기계가 언급 한 ID로보기를 찾습니다. 따라서 레이아웃의 내용을 먼저 설정하고 뷰를 초기화해야합니다. 당신이 NPE

편집하지 않으면 :

을 또한 이미 ID wightTextheightText으로 초기화됩니다 weightEheightE을 사용할 수 있습니다

필요하지 않습니다

EditText weightText = (EditText)findViewById(R.id.weightText); 
EditText heightText = (EditText)findViewById(R.id.heightText); 

있습니다. 당신이 혼란을

String weightE, heightE, ageE; 
    weightE = getString(R.id.weightText); 
    heightE = getString(R.id.heightText); 
을 방지하기 위해 같은 이름으로도 editexts이 당신이 온 클릭이있는 모든하지만

변수의 이름을 변경 : 이미 클래스 멤버이며, 이후 다시

편집 2 초기화 할 필요를 초기화하지

그리고 comapre 문자열에는 .equals 또는 .equalsIgnoreCase을 사용하십시오.

if (!weightE.equals("") && (!heightE.equals("") && (!ageE.equals("")) 
+0

편집 1 및 2에 대한 제안에 감사드립니다. 지금 작동합니다. Btw! weightE.equals ("") 부분에 대해 "!" infront는 의미합니까? – Onered

+0

@ user2943793 weightE가 ""와 같지 않은 경우 .equals가있는 항상 comapre 문자열은 false를 반환합니다. false가 true입니다. 그래서 그것이 사실이라면, if를 입력하십시오. BTW는 답을 얻는 데 도움이된다면 바로 옆에있는 체크를 클릭하여 대답을 수락합니다. – Raghunandan

1

: 미리 감사드립니다 .. 다음은 BMIcalculation.java 내 코드입니다

이동

weightE = (EditText)findViewById(R.id.weightText); 
heightE = (EditText)findViewById(R.id.heightText); 
ageE = (EditText)findViewById(R.id.ageText); 
caloriesresult = (EditText)findViewById(R.id.caloriesText); 
male = (RadioButton) findViewById(R.id.maleradio); 
female = (RadioButton) findViewById(R.id.femaleradio); 

일부 onCreate 이후

setContentView(R.layout.bmilayout_main); 

setContentView 전에보기를 찾으려고합니다. 그리고 밖으로 선언하십시오. 초기화 한 곳을 만드십시오. 그것을 수정하십시오. 희망이 도움이됩니다.

+0

고마워. 예이 도움이됩니다 :). 그 부분을 움직여서 이제 앱을 실행하고 앱에 들어갈 수 있습니다. – Onered

+0

좋은 @ user2943793 다시 문제가 발생하면 알려주세요 –

1

콘텐츠보기를 설정하기 전에 구성 요소를 초기화 할 수 없습니다. OnCreate(). 따라서 onCreate() 전에 선언하십시오. & OnCreate()에서 내용보기를 설정 한 후 모든 구성 요소를 초기화합니다.

package com.example.caloriescalculator; 


public class BMIcalculation extends Activity 
{ 
EditText weightE; 
EditText heightE ; 
EditText ageE ; 
EditText caloriesresult ; 
RadioButton male; 
RadioButton female; 

Button calories; 

EditText weightText ; 
EditText heightText ; 
TextView resultText ; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.bmilayout_main); 

weightE = (EditText)findViewById(R.id.weightText); 
heightE = (EditText)findViewById(R.id.heightText); 
ageE = (EditText)findViewById(R.id.ageText); 
caloriesresult = (EditText)findViewById(R.id.caloriesText); 
male = (RadioButton) findViewById(R.id.maleradio); 
female = (RadioButton) findViewById(R.id.femaleradio); 
calories = (Button) findViewById(R.id.caloriesButton); 


    calories.setOnClickListener(new OnClickListener() 
     { 
     @Override 
       public void onClick(View arg0) 
       {  
        // rest of your code 
+0

오. 나는 당신의 제안을 따르고 그 부분을 움직였다. 이제 작동합니다. 귀하의 신속한 회신과 큰 도움을 주셔서 감사합니다 :) – Onered

+0

도와 드리겠습니다! 내 대답은 귀하의 문제를 해결하면 그때 대답으로 받아 들일 수 있습니다. –

관련 문제