Java 当我单击“计算”按钮以显示结果时,应用程序崩溃

Java 当我单击“计算”按钮以显示结果时,应用程序崩溃,java,android,android-fragments,math,onclick,Java,Android,Android Fragments,Math,Onclick,在BMI计算器上工作,该计算器有一个旋转器,可以获得英尺/英寸以及用户的体重 问题:当我点击计算我的应用程序崩溃时,我不知道发生了什么。我知道logtcat提到了一些关于onclick的内容,尽管我已经在oncreatview上声明了按钮 日志: 04-08 13:02:27.486 12353-12353/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main Process: com.exa

在BMI计算器上工作,该计算器有一个旋转器,可以获得英尺/英寸以及用户的体重

问题:当我点击计算我的应用程序崩溃时,我不知道发生了什么。我知道logtcat提到了一些关于onclick的内容,尽管我已经在oncreatview上声明了按钮

日志:

 04-08 13:02:27.486 12353-12353/com.example.treycoco.calorietracker
 E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.treycoco.calorietracker, PID: 12353
 java.lang.NullPointerException
 at com.example.treycoco.calorietracker.BmiFrag.onClick(BmiFrag.java:98)
 at android.view.View.performClick(View.java:4438)
 at android.view.View$PerformClick.run(View.java:18422)
 at android.os.Handler.handleCallback(Handler.java:733)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:136)
 at android.app.ActivityThread.main(ActivityThread.java:5045)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:515)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
 at dalvik.system.NativeStart.main(Native Method)
BmiFrag.java

     public class BmiFrag extends Fragment implements View.OnClickListener {
     Button BmiButton;

    public static EditText heightFT;
    public static EditText heightIn;
    public static EditText weightIn;

    //adaptors spinners

    ArrayAdapter<String> HeightFeetAdapter;
    ArrayAdapter<String> WeightLBSAdapter;

    //references UI elements

    Spinner weightSpinner;
    Spinner heightSpinner;


     @Override
     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    View myView = inflater.inflate(R.layout.fragment_bmi, container, false);

    heightSpinner= (Spinner) myView.findViewById(R.id.HeightSpin);

    weightSpinner= (Spinner)myView.findViewById(R.id.WeightSpin);


    BmiButton = (Button) myView.findViewById(R.id.CalculateBmi);
    BmiButton.setOnClickListener(this);


    initializeSpinnerAdapters();
    loadLBVal();
    loadFTVal();

    return myView;
   }

       @Override
       public void onClick(View v) {
       switch (v.getId()) {

       case R.id.CalculateBmi:


            final TextView tv4 = (TextView)
       getActivity().findViewById(R.id.TFDisplayBmi);

           /* str1*/
            String getWeightIN = weightIn.getText().toString();



             /* str2*/
            String  getHeightIN = heightIn.getText().toString();

            String getHeightFT = heightFT.getText().toString();



            if (TextUtils.isEmpty(getWeightIN)) {



                weightIn.setError("Please enter your weight");
                weightIn.requestFocus();
                return;
            }

            else if (TextUtils.isEmpty(getHeightIN)) {
                heightIn.setError("Please enter your height in Inches");
                heightIn.requestFocus();
                return;
            }

            else if (TextUtils.isEmpty(getHeightFT)) {
                heightFT.setError("Please enter your height in Feet");
                heightFT.requestFocus();
                return;
            }


            else {

               float weight = getSelectedWeight();
                float height = getSelectedHeight();


                float bmiValue = calculateBMI(weight,height);

                String bmiInterpretation = interpretBMI(bmiValue);

                tv4.setText(String.valueOf(bmiValue + "-" +
                bmiInterpretation));


            }



            break;

    }
    }

     // retrieve the weight from the spinner control converted to kg
          public float getSelectedWeight() {
          String selectedWeightValue =
          (String)weightSpinner.getSelectedItem();

          return (float) (Float.parseFloat(selectedWeightValue) * 
          0.45359237);
      }


          public float getSelectedHeight() {
          String selectedHeightValue = 
          (String)heightSpinner.getSelectedItem();

         // the position is feets and inches, so convert to meters andreturn
        String feets = selectedHeightValue.substring(0, 1);
        String inches = selectedHeightValue.substring(2, 4);
        return (float) (Float.parseFloat(feets) * 0.3048) +
                (float) (Float.parseFloat(inches) * 0.0254);

     }


       private float calculateBMI(float weight, float height ) {

       //weight * 703f / (float)Math.pow(heightIN+12f*v,2);
       float bmi=  (weight / (height * height));

        float total= Math.round(bmi);



          return  total;
    }


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



         public void loadLBVal() {
         weightSpinner.setAdapter(WeightLBSAdapter);
         // set the default lib value
        weightSpinner.setSelection(WeightLBSAdapter.getPosition("170"));
        }


        // load the feets value range to the height spinner
       public void loadFTVal() {
       heightSpinner.setAdapter(HeightFeetAdapter);
       // set the default value to feets
      heightSpinner.setSelection(HeightFeetAdapter.getPosition("5\"05'"));
    }

         public void initializeSpinnerAdapters() {

         String[] weightLibs = new String[300];

               for (int i = 1; i <= 300; i ++) {
             weightLibs[k--] = String.format("%3d", i);
             }
        // initialize the weightLibsAdapter with the weightLibs values
        WeightLBSAdapter = new ArrayAdapter<String>(getContext(), 
        android.R.layout.simple_list_item_activated_1 , weightLibs);




        String[] heightFeets = new String[60];
       // loading 3"0' to 7"11' to the height in feet/inch
          k = 59;
          for (int i = 3; i < 8; i ++) {
          for (int j = 0; j < 12; j ++) {
            heightFeets[k--] = i + "\"" + String.format("%02d", j) + "'";
         }
        }
        // initialize the heightFeetAdapter with the heightFeets values
       HeightFeetAdapter = new ArrayAdapter<String>(getContext(), 
       android.R.layout.simple_list_item_activated_1, heightFeets);

      }


             @Override
           public void onActivityCreated(Bundle savedInstanceState) {
           super.onActivityCreated(savedInstanceState);
       }

            @Override
            public void onDestroy() {
            super.onDestroy();

           }

            @Override
            public void onDetach() {
            super.onDetach();
           }
         }
公共类BmiFrag扩展片段实现View.OnClickListener{
按钮按钮;
公共静态编辑文本高度;
公共静态编辑文本高度;
公共静态编辑文本权重;
//转接器纺纱机
阵列自适应高度传感器;
阵列自适应加权自适应;
//引用UI元素
旋转器重量旋转器;
旋转器高度旋转器;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图myView=充气机。充气(R.layout.fragment\u bmi,容器,false);
heightSpinner=(Spinner)myView.findviewbyd(R.id.HeightSpin);
weightSpinner=(微调器)myView.findViewById(R.id.WeightSpin);
BmiButton=(Button)myView.findviewbyd(R.id.CalculateBmi);
bmibuton.setOnClickListener(此);
初始化InnerAdapters();
loadLBVal();
loadFTVal();
返回myView;
}
@凌驾
公共void onClick(视图v){
开关(v.getId()){
案例R.id.CalculateBmi:
最终文本视图tv4=(文本视图)
getActivity().findViewById(R.id.TFDisplayBmi);
/*str1*/
字符串getWeightIN=weightIn.getText().toString();
/*str2*/
字符串getHeightIN=heightIn.getText().toString();
字符串getHeightFT=heightFT.getText().toString();
if(TextUtils.isEmpty(getWeightIN)){
设置错误(“请输入您的体重”);
requestFocus();
返回;
}
else if(TextUtils.isEmpty(getHeightIN)){
heightIn.setError(“请以英寸为单位输入您的高度”);
heightIn.requestFocus();
返回;
}
else if(TextUtils.isEmpty(getHeightFT)){
heightFT.setError(“请以英尺为单位输入您的高度”);
heightFT.requestFocus();
返回;
}
否则{
浮动重量=getSelectedWeight();
浮动高度=getSelectedHeight();
浮动BMI值=计算BMI(体重、身高);
字符串bmi解释=解释bmi(bmi值);
tv4.setText(String.valueOf(bmiValue+“-”+
(释义),;
}
打破
}
}
//从微调器控件检索转换为kg的重量
公共浮点数getSelectedWeight(){
字符串选择的权重值=
(字符串)weightSpinner.getSelectedItem();
返回(浮点)(float.parseFloat(selectedWeightValue)*
0.45359237);
}
公共浮点数getSelectedHeight(){
字符串selectedHeightValue=
(字符串)heightSpinner.getSelectedItem();
//位置为英尺和英寸,因此转换为米和英寸
String feets=selectedHeightValue.substring(0,1);
字符串英寸=所选高度值。子字符串(2,4);
返回(浮动)(浮动。浮动(英尺)*0.3048)+
(浮动)(浮动。浮动(英寸)*0.0254);
}
专用浮子计算器BMI(浮子重量、浮子高度){
//重量*703f/(浮子)数学功率(高度+12f*v,2);
浮动体重指数=(体重/(身高*身高));
浮动总额=数学整数(bmi);
返回总数;
}
专用字符串解释BMI(浮点BMI值){
如果(BMI值<16){
返回“严重体重不足”;
}否则如果(BMI值<18.5){
返回“减持”;
}否则如果(BMI值<25){
返回“正常”;
}否则如果(BMI值<30){
返回“超重”;
}否则{
返回“肥胖”;
}
}
公共void loadLBVal(){
设置适配器(WeightLBSAdapter);
//设置默认的lib值
weightSpinner.setSelection(WeightLBSAdapter.getPosition(“170”);
}
//将feets值范围加载到高度微调器
公共void loadFTVal(){
heightSpinner.setAdapter(HeightFeetAdapter);
//将默认值设置为feets
heightSpinner.setSelection(HeightFeetAdapter.getPosition(“5\“05”);
}
public void initializeSpinnerAdapters(){
字符串[]权重libs=新字符串[300];

对于(int i=1;i您将回调函数设置为BmiButton的Click Listener作为“OnCreateView()”方法,当您在此行中声明“this”时:

BmiButton.setOnClickListener(this);
将“this”更改为“onClick(View v)”,如下面的示例所示,就可以开始了

BmiButton.setOnClickListener(onClick(View v));

更新:尽管这将需要较少的编辑,但Nitesh Kumar的解决方案是最好的方法,因为它不需要每次用户单击按钮时都检查开关语句,为每个单击的视图设置一个回调函数。

您将回调函数设置为BmiButton的Click Listener作为“OnCreateView()方法,当您在此行中声明“this”时:

BmiButton.setOnClickListener(this);
将“this”更改为“onClick(View v)”,如下面的示例所示,就可以开始了

BmiButton.setOnClickListener(onClick(View v));

更新:虽然这将需要您更少的编辑,但尼特什·库马尔的解决方案是最好的方法,因为它不需要您在每次用户单击按钮时都检查开关语句,为每个单击的视图设置一个回调函数。

没有初始化任何
编辑文本
,因此在按钮cl上ick wh