Как сохранить результат из расчета в базу данных Firebase - PullRequest
0 голосов
/ 13 января 2019

Я разрабатываю приложение калькулятора ИМТ, чтобы сохранить результат bmi, а также рост, вес и дату, время. К сожалению, он сохранил результат только для роста и веса, и страница не будет вычислять bmi (при нажатии на кнопку вычисления) и не сохранит результат bmi в базе данных (он сохранил только рост и вес, а не результат). Пожалуйста, действительно нужна помощь. Спасибо за ваше время. Interface

databaseBMIs = FirebaseDatabase.getInstance().getReference("BMIs");

    height = (EditText) findViewById(R.id.height);
    weight = (EditText) findViewById(R.id.weight);
    result = (TextView) findViewById(R.id.result);

    saveBMI = (Button) findViewById(R.id.saveBMI);
    calc = (Button) findViewById(R.id.calc);

    saveBMI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addBMI();
        }
    });
}

public void bmiCalculator(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);

    }
}

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

    if (Float.compare(bmi, 15f) <= 0) {
        bmiLabel = getString(R.string.very_severely_underweight);
    } else if (Float.compare(bmi, 15f) > 0 && Float.compare(bmi, 16f) <= 0) {
        bmiLabel = getString(R.string.severely_underweight);
    } else if (Float.compare(bmi, 16f) > 0 && Float.compare(bmi, 18.5f) <= 0) {
        bmiLabel = getString(R.string.underweight);
    } else if (Float.compare(bmi, 18.5f) > 0 && Float.compare(bmi, 25f) <= 0) {
        bmiLabel = getString(R.string.normal);
    } else if (Float.compare(bmi, 25f) > 0 && Float.compare(bmi, 30f) <= 0) {
        bmiLabel = getString(R.string.overweight);
    } else if (Float.compare(bmi, 30f) > 0 && Float.compare(bmi, 35f) <= 0) {
        bmiLabel = getString(R.string.obese_class_i);
    } else if (Float.compare(bmi, 35f) > 0 && Float.compare(bmi, 40f) <= 0) {
        bmiLabel = getString(R.string.obese_class_ii);
    } else {
        bmiLabel = getString(R.string.obese_class_iii);
    }

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

}

public void addBMI() {
    String height_bmi = height.getText().toString();
    String weight_bmi = weight.getText().toString();
    String result_bmi = result.getText().toString();
    calendar = Calendar.getInstance();
    simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    final String datetime = simpleDateFormat.format(calendar.getTime());

    if (!TextUtils.isEmpty(height_bmi)) {

    } else {
        Toast.makeText(this, "Please enter your height", Toast.LENGTH_LONG).show();
    }

    if (!TextUtils.isEmpty(weight_bmi)) {

        String id = databaseBMIs.push().getKey();

        BMI Bmi = new BMI(id, height_bmi, weight_bmi, result_bmi, datetime);

        databaseBMIs.child(id).setValue(Bmi);

        Toast.makeText(this, "BMI added", Toast.LENGTH_LONG).show();

    } else {
        Toast.makeText(this, "Please enter your weight", Toast.LENGTH_LONG).show();
    }
}

XML

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/gradient_background4"
    android:orientation="vertical"
    tools:context=".Page3Activity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="65dp"
        app:cardCornerRadius="10dp"
        app:cardElevation="3dp"
        app:cardUseCompatPadding="true"
        app:cardPreventCornerOverlap="false">

        <RelativeLayout
            android:background="@color/white"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tv1"
                android:textStyle="bold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:gravity="center"
                android:text="Height"
                android:layout_marginTop="30dp"/>

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

            <TextView
                android:id="@+id/tv2"
                android:layout_below="@id/height"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:gravity="center"
                android:textStyle="bold"
                android:layout_gravity="center_horizontal"
                android:text="Weight"
                android:layout_marginTop="50dp"/>

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

            <Button
                android:id="@+id/calc"
                android:layout_below="@id/weight"
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:layout_marginLeft="30dp"
                android:text="Calculate"
                android:background="#df5d46"
                android:onClick="bmiCalculator"
                android:layout_gravity="center_horizontal"/>

            <Button
                android:id="@+id/saveBMI"
                android:layout_below="@id/weight"
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:layout_marginLeft="160dp"
                android:text="Save"
                android:background="#df5d46"
                android:layout_gravity="center_horizontal"/>

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


        </RelativeLayout>
    </android.support.v7.widget.CardView>

</RelativeLayout>

Ответы [ 2 ]

0 голосов
/ 13 января 2019

Вы должны вызвать метод displayBMI () В конце метода addBMI

Например

public void bmiCalculator(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)//<<<<<Very important

    }
}

Успешно Друг * * 1006

0 голосов
/ 13 января 2019

В коде, которым вы поделились bmiCalculator () никогда не вызывается и равен displayBMI () . Эти методы необходимы для отображения результата. Метод bmiCalculator () , вероятно, следует вызывать в addBMI () , а затем вызывать displayBMI () с этими результатами.

Код должен выглядеть примерно так:

var calculation = bmiCalculator();
displayBMI(calculation);
...