有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

应用程序在点击按钮时崩溃,Android Studio(Java)

Hello fellow programmers!
I have a very disturbing situation here...I'm developing an Android App with several activities.In them I have buttons.The app itself is for measuring calories and other sports releated stuff.
I have a calorie calculator which I have built in the app,spread across 2 activities.In activity 1,the calculator measures the Basal Metabolic Rate and In the second activity,the app calculates the calories needed,when clicking a button for the desired activity level.My app crashes in the second activity,when clicking "Sedentary" button and I have no clue why,because these buttons are built just like the buttons in my first activity.I'll post photos and my code so you can get orientation.
Btw,the app crashes also when clicking "Null Data" in the first activity with the BMR...The button doesn't have any coding on it and does nothing.I'm not calling calculate() method in the second activity,instead I tried doing the button click in the main method,but it still didn't work.

各位程序员好! 我这里有一个非常令人不安的情况。。。我正在开发一个安卓应用程序,其中包含几个活动。里面有纽扣。该应用程序本身用于测量卡路里和其他与运动相关的东西。 我有一个卡路里计算器,我已经在应用程序中建立了它,分布在两个活动中。在活动1中,计算器测量基础代谢率,在第二项活动中,当点击所需活动水平的按钮时,应用程序计算所需的卡路里。我的应用程序在第二个活动中崩溃,当点击“久坐”按钮时,我不知道为什么,因为这些按钮与我第一个活动中的按钮一样。我会发布照片和代码,这样你就可以了解情况了。 顺便说一句,当使用BMR在第一个活动中单击“空数据”时,应用程序也会崩溃。。。按钮上没有任何编码,什么也不做。在第二个活动中,我没有调用calculate()方法,而是尝试在主方法中单击按钮,但仍然不起作用First ActivitySecond Activity

`package com.petartonkov.foodandsportsinfo;

import 安卓.content.Intent;
import 安卓.os.Bundle;
import 安卓.os.Parcelable;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.support.v7.widget.Toolbar;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.CheckBox;
import 安卓.widget.EditText;
import 安卓.widget.TextView;

public class CalorieCalculator extends AppCompatActivity {

    public Button nextstepbtn;
    public TextView BMR;
    public EditText height;
    public EditText weight;
    public EditText age;

    public void calculate() {
       final Button calculateBMR = (Button) findViewById(R.id.CalcBtn);
       final TextView BMR = (TextView) findViewById(R.id.textView_BMR);
       final EditText weight = (EditText) findViewById(R.id.editText_weight);
       final EditText height = (EditText) findViewById(R.id.editText_height);
       final EditText age = (EditText) findViewById(R.id.editText_age);
        assert calculateBMR != null;
        calculateBMR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                assert weight != null;
                float weight1 = Float.parseFloat(weight.getText().toString());
                assert height != null;
                float height1 = Float.parseFloat(height.getText().toString());
                assert age != null;
                float age1 = Float.parseFloat(age.getText().toString());
                float BMR1 = (13.75f * weight1 + 5.003f * height1 - 6.755f * age1) + 66.75f;
                assert BMR != null;
                BMR.setText(Float.toString(BMR1));
            }
        });
    }
    public void calculate1() {
        final Button calculateBMR = (Button) findViewById(R.id.CalcBtnFemale);
        final TextView BMR = (TextView) findViewById(R.id.textView_BMR);
        final EditText weight = (EditText) findViewById(R.id.editText_weight);
        final EditText height = (EditText) findViewById(R.id.editText_height);
        final EditText age = (EditText) findViewById(R.id.editText_age);
        assert calculateBMR != null;
        calculateBMR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                assert weight != null;
                float weight1 = Float.parseFloat(weight.getText().toString());
                assert height != null;
                float height1 = Float.parseFloat(height.getText().toString());
                assert age != null;
                float age1 = Float.parseFloat(age.getText().toString());
                float BMR1 = (9.563f * weight1 + 1.85f * height1 - 4.676f * age1) + 655.1f;
                assert BMR != null;
                BMR.setText(Float.toString(BMR1));
            }
        });
    }
    public void init4(){
        nextstepbtn = (Button)findViewById(R.id.NextStepBtn);
        nextstepbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(getBaseContext(), CalorieCalculatorSecondActivity.class);
                intent1.putExtra("BMR", (Parcelable) BMR);
                startActivity(intent1);
            }
        });


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calorie_calculator);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
            init4();
calculate();
        calculate1();
    }

}
`

      `  package com.petartonkov.foodandsportsinfo;

    import 安卓.os.Bundle;
    import 安卓.support.design.widget.FloatingActionButton;
    import 安卓.support.design.widget.Snackbar;
    import 安卓.support.v7.app.AppCompatActivity;
    import 安卓.support.v7.widget.Toolbar;
    import 安卓.view.View;
    import 安卓.widget.Button;
    import 安卓.widget.TextView;

    public class CalorieCalculatorSecondActivity extends CalorieCalculator {

    public void totalcalories() {
        final Button calculateBtn = (Button) findViewById(R.id.button_sedentary);
        final TextView totalcalories = (TextView) findViewById(R.id.textView_totalcalories);
        final TextView BMR = (TextView) findViewById(R.id.textView_BMR);
        assert calculateBtn != null;
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                assert BMR != null;
                float BMR2 = Float.parseFloat(BMR.getText().toString());
                float totalcalories1 = BMR2 * 1.2f;
                assert totalcalories != null;
                totalcalories.setText(Float.toString(totalcalories1));
            }
        });
    }
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_calorie_calculator_second);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            Bundle extras = getIntent().getExtras();
    final Button calcBtn = (Button)findViewById(R.id.button_sedentary);
            final TextView totalcalories2 = (TextView)findViewById(R.id.textView_totalcalories);
            final TextView BMR1 = (TextView) findViewById(R.id.textView_BMR);
            assert calcBtn != null;
            calcBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    assert BMR1 != null;
                    float BMR3 = Float.parseFloat(BMR1.getText().toString());
                    float totalcalories4 = BMR3 * 1.2f;
                    assert totalcalories2 != null;
                    totalcalories2.setText(Float.toString(totalcalories4));
                }
            });
        }
    }
`

`

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:text="Enter your data below to calculate your BMR(Basal Metabolic Rate) and then enter your level of physical activity to determine your daily calorie needs.BMR-this number is the calories needed from the body to maintain basic living functions."
        安卓:id="@+id/textView2"
        安卓:textColor="#040404"
        安卓:layout_alignParentTop="true"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:layout_marginTop="30dp" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="go to next step"
        安卓:id="@+id/NextStepBtn"
        安卓:layout_alignParentBottom="true"
        安卓:layout_centerHorizontal="true" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:text="BMR:"
        安卓:id="@+id/textView11"
        安卓:textColor="#070707"
        安卓:layout_below="@+id/CalcBtn"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:layout_marginTop="26dp" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:text="CAL"
        安卓:id="@+id/textView13"
        安卓:layout_alignTop="@+id/textView_BMR"
        安卓:layout_centerHorizontal="true"
        安卓:textColor="#980606" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="NULL DATA"
        安卓:id="@+id/btn_nulldata"
        安卓:layout_alignBaseline="@+id/NextStepBtn"
        安卓:layout_alignBottom="@+id/NextStepBtn"
        安卓:layout_alignRight="@+id/textView2"
        安卓:layout_alignEnd="@+id/textView2"
        安卓:onClick="onCheckboxClicked"/>


    <EditText
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:inputType="numberDecimal"
        安卓:ems="10"
        安卓:id="@+id/editText_age"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:layout_marginTop="27dp"
        安卓:hint="Enter age"
        安卓:layout_below="@+id/textView2" />

    <EditText
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:inputType="numberDecimal"
        安卓:ems="10"
        安卓:id="@+id/editText_weight"
        安卓:layout_below="@+id/editText_age"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:hint="Enter weight(In KG)"
        安卓:layout_alignRight="@+id/NextStepBtn"
        安卓:layout_alignEnd="@+id/NextStepBtn" />

    <EditText
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:inputType="numberDecimal"
        安卓:ems="10"
        安卓:id="@+id/editText_height"
        安卓:layout_below="@+id/editText_weight"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:hint="Enter height(In CM)" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:id="@+id/textView_BMR"
        安卓:layout_alignTop="@+id/textView11"
        安卓:layout_toLeftOf="@+id/NextStepBtn"
        安卓:layout_toStartOf="@+id/NextStepBtn"
        安卓:textColor="#980606" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="CALCULATE BMR-MALE"
        安卓:id="@+id/CalcBtn"
        安卓:background="?attr/colorPrimary"
        安卓:textColor="#ffffff"
        安卓:layout_marginTop="31dp"
        安卓:layout_below="@+id/editText_height"
        安卓:layout_toLeftOf="@+id/textView13"
        安卓:layout_toStartOf="@+id/textView13" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="CALCULATE BMR-FEMALE"
        安卓:id="@+id/CalcBtnFemale"
        安卓:background="?attr/colorPrimary"
        安卓:textColor="#ffffff"
        安卓:layout_alignBottom="@+id/CalcBtn"
        安卓:layout_toRightOf="@+id/textView13"
        安卓:layout_toEndOf="@+id/textView13" />


</RelativeLayout>`

`

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:text="SELECT YOUR LEVEL OF PHYSICAL ACTIVITY:"
        安卓:id="@+id/textView10"
        安卓:layout_alignParentTop="true"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="sedentary"
        安卓:id="@+id/button_sedentary"
        安卓:layout_below="@+id/textView10"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:clickable="true"
        安卓:enabled="true"
        安卓:onClick="setContentView" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="moderately active"
        安卓:id="@+id/button_moderatelyactive"
        安卓:layout_alignTop="@+id/button_sedentary"
        安卓:layout_alignRight="@+id/textView14"
        安卓:layout_alignEnd="@+id/textView14" />

    <Button
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="Very active"
        安卓:id="@+id/button_veryactive"
        安卓:layout_below="@+id/button_sedentary"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="Extremely active"
        安卓:id="@+id/button_extremelyactive"
        安卓:layout_alignBottom="@+id/button_veryactive"
        安卓:layout_alignLeft="@+id/button_moderatelyactive"
        安卓:layout_alignStart="@+id/button_moderatelyactive" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceSmall"
        安卓:text="Sedentary - Little or no exercise,little walking"
        安卓:id="@+id/textView14"
        安卓:layout_below="@+id/button_veryactive"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:textColor="#e10e0e" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceSmall"
        安卓:text="Lighty active - light exercise 1-3 times/week + walking"
        安卓:id="@+id/textView15"
        安卓:layout_below="@+id/textView14"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:textColor="#e10e0e" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceSmall"
        安卓:text="Moderately active - exercise 3-5 times/week + walking"
        安卓:id="@+id/textView16"
        安卓:layout_below="@+id/textView15"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:textColor="#e10e0e" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceSmall"
        安卓:text="Very active - hard exercise 5-7 times/week + walking"
        安卓:id="@+id/textView17"
        安卓:textColor="#e10e0e"
        安卓:layout_below="@+id/textView16"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:text="TOTAL CALORIES NEEDED:"
        安卓:id="@+id/textView18"
        安卓:layout_centerVertical="true"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:textColor="#080808" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:id="@+id/textView_totalcalories"
        安卓:layout_alignTop="@+id/textView18"
        安卓:layout_toRightOf="@+id/textView18"
        安卓:layout_toEndOf="@+id/textView18"
        安卓:editable="false"
        安卓:enabled="false"
        安卓:text="0" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceMedium"
        安卓:text="CAL"
        安卓:id="@+id/textView20"
        安卓:layout_alignBottom="@+id/textView_totalcalories"
        安卓:layout_alignParentRight="true"
        安卓:layout_alignParentEnd="true"
        安卓:textColor="#090909" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="NULL DATA"
        安卓:id="@+id/btn_nulldata2"
        安卓:layout_marginBottom="48dp"
        安卓:layout_alignParentBottom="true"
        安卓:layout_alignRight="@+id/button_sedentary"
        安卓:layout_alignEnd="@+id/button_sedentary" />

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textAppearance="?安卓:attr/textAppearanceSmall"
        安卓:text="Extra active - hard exercise 5-7 times/week + physical job + walking"
        安卓:id="@+id/textView3"
        安卓:textColor="#e10e0e"
        安卓:layout_below="@+id/textView17"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true" />

    <Button
        style="?安卓:attr/buttonStyleSmall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="Lightly active"
        安卓:id="@+id/button"
        安卓:layout_alignBottom="@+id/button_extremelyactive"
        安卓:layout_alignParentRight="true"
        安卓:layout_alignParentEnd="true"
        安卓:layout_toRightOf="@+id/button_extremelyactive"
        安卓:layout_toEndOf="@+id/button_extremelyactive" />

</RelativeLayout>`

`

                                                                                 --------- beginning of crash
06-14 06:10:35.167 2481-2481/com.petartonkov.foodandsportsinfo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: com.petartonkov.foodandsportsinfo, PID: 2481
                                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence 安卓.widget.TextView.getText()' on a null object reference
                                                                                     at com.petartonkov.foodandsportsinfo.CalorieCalculatorSecondActivity$2.onClick(CalorieCalculatorSecondActivity.java:44)
                                                                                     at 安卓.view.View.performClick(View.java:5198)
                                                                                     at 安卓.view.View$PerformClick.run(View.java:21147)
                                                                                     at 安卓.os.Handler.handleCallback(Handler.java:739)
                                                                                     at 安卓.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at 安卓.os.Looper.loop(Looper.java:148)
                                                                                     at 安卓.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                     at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:616)

`


共 (4) 个答案

  1. # 1 楼答案

    要将值从一个活动传递到另一个活动,可以使用Intent extra

    Intent extra是您希望从一个活动传递到另一个活动的附加信息包。你可以创建这样的附加功能

    //First Activity
    Intent i = new Intent(FirstActiviy.this, SecondActivity.class);   
    String value = "some string you want to put in the extra";
    int value2 = 14
    
    //put extra as key-value pairs
    i.putExtra("KEY", value);
    i.putExtra("KEY2", value2);
    
    startActivity(i);
    
    
    //Second activity 
    
    //Get the values from previous Activity by keys you set 
    String stringValueFromPreviousActivity = getIntent().getStringExtra("key");
    
    //Note: when you getting integer as the second parameter pass the default value if there is no passed integer
    int intValueFromPreviousActiviy = getIntent().getIntExtra("key",4);
    
  2. # 2 楼答案

    这是我扔的

         calcBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    assert BMR1 != null;
                    float BMR3 = Float.parseFloat(BMR1.getText().toString());
                    float totalcalories4 = BMR3 * 1.2f;
                    assert totalcalories2 != null;
                    totalcalories2.setText(Float.toString(totalcalories4));
                }
            });
    

    在第二个活动布局中没有id为TextView_BMR的TextView(BMR1)

  3. # 3 楼答案

    我试着在一个活动中设置计算器。。。我重新调整了按钮,你猜怎么着。。?虽然我在BMR TextView中有一个字符串,但我在BMR TextView中的浮点值为空。为什么会这样?在第一个活动中,我用另一种方法编写了总卡路里的代码

    public void calculatetotalcalories()
        {
            final Button calcbtn_sedentary = (Button)findViewById(R.id.button_sedentary);
            final TextView totalcalories = (TextView)findViewById(R.id.textView_totalcalories);
            calcbtn_sedentary.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    float BMRconverted= Float.parseFloat(String.valueOf(BMR));
                    float totalcalories1 =BMRconverted*1.2f;
                    totalcalories.setText(Float.toString(totalcalories1));
                }
            });
    
  4. # 4 楼答案

    我解决了这个问题。在活动开始时,它是一个空对象引用。现在一切都好了