MCris
MCris

Reputation: 21

java.lang.IllegalStateException: Could not find method in a parent or ancestor Context

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

Upvotes: 1

Views: 540

Answers (2)

Gaurav Bansal
Gaurav Bansal

Reputation: 644

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.

Upvotes: 0

Ali Amini
Ali Amini

Reputation: 416

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 ;)

Upvotes: 1

Related Questions