使用BMI计算器,该计算器的旋转器可以达到英尺/英寸以及用户的体重。
问题:当我点击计算我的应用程序崩溃时,我不确定发生了什么。我知道logtcat提到了关于onclick的一些东西,尽管我在oncreatview上声明了这个按钮。
logcat的:
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();
}
}
再次感谢。我还在学习Android Studio和Java,这是我第一次使用应用程序。此外,如果数学看起来我道歉。我正在研究不同的公式。
答案 0 :(得分:2)
当您执行此操作时尚未初始化任何edittext
因此按下按钮
String getWeightIN = weightIn.getText().toString();
你得到空指针异常。像按钮一样初始化编辑文本,一切都会很好
答案 1 :(得分:1)
您正在将回调函数设置为BmiButton的Click Listener作为&#34; OnCreateView()&#34;方法,当你陈述&#34;这个&#34;在这一行:
BmiButton.setOnClickListener(this);
改变&#34;这&#34;到&#34; onClick(查看v)&#34;,如下例所示,你很高兴。
BmiButton.setOnClickListener(onClick(View v));
更新:虽然这需要您减少编辑,但Nitesh Kumar的解决方案是最好的方法,因为每次用户点击按钮时,它都不会要求您查看switch语句,设置单击每个视图的一个回调函数。
答案 2 :(得分:1)
首先在oncreateview()方法中初始化与xml相关的所有对象,然后就可以使用这个对象了。 并检查在xml中使用的所有控件视图,如edittext或textview 所以检查所有要初始化的对象。
BmiButton.setOnClickListener(本);
下面的代码是正确的,所以不需要改变。