1

I am trying to make an app for my homework and I found this BMI calculator that really fits my idea. So I am trying to add it to my project but I get an error that says this when I press the button to calculateBMI:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.assignment.careys, PID: 5827
    java.lang.IllegalStateException: Could not find method calculateBMI(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'calc'
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:423)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:380)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I followed this tutorial here https://www.ssaurel.com/blog/learn-to-create-a-bmi-calculator-app-for-android/ But I made a new class for my calculator, called "CalculateBMI", because I am already using "MainActivity"

CalculateBMI.java:

public class CalculateBMI extends AppCompatActivity {

    private EditText height;
    private EditText weight;
    private TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculate_bmi);
        height = (EditText) findViewById(R.id.height);
        weight = (EditText) findViewById(R.id.weight);
        result = (TextView) findViewById(R.id.result);
    }

    public void calculateBMI(View v) {
        String heightStr = height.getText().toString();
        String weightStr = weight.getText().toString();

        if (heightStr != null && !"".equals(heightStr)
                && weightStr != null  &&  !"".equals(weightStr)) {
            float heightValue = Float.parseFloat(heightStr) / 100;
            float weightValue = Float.parseFloat(weightStr);

            float bmi = weightValue / (heightValue * heightValue);

            displayBMI(bmi);
        }
    }

    public void displayBMI(float bmi) {
        String bmiLabel = "";

        if (Float.compare(bmi, 15f) <= 0) {
            bmiLabel = "";
        } else if (Float.compare(bmi, 15f) > 0  &&  Float.compare(bmi, 16f) <= 0) {
            bmiLabel = "";
        } else if (Float.compare(bmi, 16f) > 0  &&  Float.compare(bmi, 18.5f) <= 0) {
            bmiLabel = "";
        } else if (Float.compare(bmi, 18.5f) > 0  &&  Float.compare(bmi, 25f) <= 0) {
            bmiLabel = "";
        } else if (Float.compare(bmi, 25f) > 0  &&  Float.compare(bmi, 30f) <= 0) {
            bmiLabel = "";
        } else if (Float.compare(bmi, 30f) > 0  &&  Float.compare(bmi, 35f) <= 0) {
            bmiLabel = "";
        } else if (Float.compare(bmi, 35f) > 0  &&  Float.compare(bmi, 40f) <= 0) {
            bmiLabel = "";
        } else {
            bmiLabel = "";
        }

        bmiLabel = bmi + "\n\n" + bmiLabel;
        result.setText(bmiLabel);
    }}

calculate_bmi.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/calculate_bmi"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.assignment.asistentdigital.entity.CalculateBMI">

    <EditText
        android:id="@+id/weight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:ems="6"
        android:inputType="number|numberDecimal"
        android:textSize="14sp"/>

    <EditText
        android:id="@+id/height"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:ems="6"
        android:inputType="number|numberDecimal"
        android:textSize="14sp"/>

    <Button
        android:id="@+id/calc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="25dp"
        android:onClick="calculateBMI"
        android:text="calculeaza"/>

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:layout_marginTop="25dp"
        android:textSize="20sp"/>

</LinearLayout> 

I wanted to include this xml in another one, and calculate and display the body mass index. And the problem is everytime I press the button to calculate, my app crashes and it give me the error

MCris
  • 21
  • 3
  • 1
    "But I made a new class for my calculator, called "CalculateBMI", because I am already using "MainActivity"" -- which activity are you showing? Usually, a layout named `activity_main` is used by a `MainActivity` class. You appear to also be using it in your `CalculateBMI` class. If that is the case -- you are using this layout in both activities, then when you click the `calc` button in `MainActivity`, you will crash with this error, as `MainActivity` (presumably) does not have a `calculateBMI()` method. – CommonsWare Jun 22 '19 at 15:19
  • okay, now i understand why my program is confused, but i created a new XML file and i named it `calculate_bmi`, I made sure I changed `setContentView` and I have the same error on click :( – MCris Jun 22 '19 at 15:28
  • As I asked originally, which activity are you showing? – CommonsWare Jun 22 '19 at 15:44
  • so sorry, I missed the question. I am using `CalculateBMI`, I did not mix `MainActivity` in this. also, I am new to this so I may missunderstand things, I apologize – MCris Jun 22 '19 at 15:50
  • At this point, probably you should update your question. Show your current code, your current layout, and provide the complete stack trace (not just the first line, as you have now). – CommonsWare Jun 22 '19 at 16:40
  • Is there any reason why you’re using the `android:onClick` attribute when it’s preferred to do it programmatically in your activity code? (EDIT: I just learnt that setting that attribute essentially sets the `OnClickListener` for you: https://stackoverflow.com/questions/4153517/how-exactly-does-the-androidonclick-xml-attribute-differ-from-setonclicklistene) – Edric Jun 22 '19 at 16:47
  • @CommonsWare thank you, i just did that – MCris Jun 22 '19 at 17:24
  • @Edric I just followed the tutorial, I will check the link, thanks! – MCris Jun 22 '19 at 17:25
  • Well, everything seems fine. The only explanation I can think of is that you are still looking at `MainActivity`, with its copy of `activity_main`, where you had the BMI layout but lacked the `calculateBMI()` method. I was hoping to get confirmation of what activity class you were using from the stack trace, but that information is not available there. :-( – CommonsWare Jun 22 '19 at 17:38
  • @CommonsWare well thank you for your time and help :), I will do more research on this, maybe I'll fix it somehow – MCris Jun 22 '19 at 17:50

2 Answers2

1

1: in CalculateBMI.java change change setContentView(R.layout.activity_main); to setContentView(R.layout.calculate_bmi);

2: set click listener for calc button in CalculateBMI.java

private Button CalcBtn;
.
.
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    height = (EditText) findViewById(R.id.height);
    weight = (EditText) findViewById(R.id.weight);
    result = (TextView) findViewById(R.id.result);
    CalcBtn = (Button) findViewById(R.id.calc);
    CalcBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculateBMI();
            }
        });
}

change calculateBMI method to:

private void calculateBMI() {
    String heightStr = height.getText().toString();
    String weightStr = weight.getText().toString();
    if (heightStr != null && !"".equals(heightStr)
            && weightStr != null  &&  !"".equals(weightStr)) {
        float heightValue = Float.parseFloat(heightStr) / 100;
        float weightValue = Float.parseFloat(weightStr);
        float bmi = weightValue / (heightValue * heightValue);
        displayBMI(bmi);
    }
}

it will work fine ;)

Ali Amini
  • 356
  • 1
  • 3
  • 12
  • Question is about achieving this using xml. – Gaurav Bansal Jun 23 '19 at 11:38
  • can you tell more about the problem – Ali Amini Jun 24 '19 at 08:17
  • @AliAmini I have to build an app about health and I wanted to add this calculator into my app, I followed the tutorial and something it's not working. Everything I do ends up with this error!!! The deadline is july 2nd, and this calculator would have secured me a good grade, so I really wanna make it work, but nothing seems to work for me. – MCris Jun 24 '19 at 17:30
  • https://github.com/iasjem/bmi-calculator-android this is a simple source of BMI calculate try to customize it hopefully help you – Ali Amini Jun 25 '19 at 08:20
0

I tried your code and it's working fine for me, the possible mistake which I think you are doing, that you have included layout file of calculate_bmi into activity_main xml and used this xml in MainActivity and still MainActivity is defined as the launcher activity in your mainfest.

So, When you launch your application, Main activity display your layout but when you click on the button, it does not find that method into MainActivity class.

So Please ensure that you are doing one of below 2 things to achieve the same.

  1. Make change this into your AndroidManifest.xml

       <activity android:name=".MainActivity">
    
        </activity>
    
        <activity android:name=".CalculateBMI">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    

OR

  1. Define CalculateBMI method into MainActivity.
Gaurav Bansal
  • 604
  • 5
  • 11