Попробуйте Catch с несколькими EditTexts, взаимодействуя с OnClick - PullRequest
0 голосов
/ 09 ноября 2019

Это мой первый вопрос, и у меня минимальный опыт работы с этим личным проектом, но я приложу все усилия, чтобы изучить его, поэтому здесь начинается моя проблема.

Я пытаюсь заставить мое приложение перестать падать, когдаEditTexts не имеет пользовательского ввода, и поэтому я реализовал метод trycatch. Тем не менее, я считаю, что я, возможно, плохо реализовал их для 4 editTexts в действии и не позволил слушателю onClick получить доступ к переменным и вычислениям. Похоже, что после этой реструктуризации onClick не получил доступ к публичному void caudalinput.

package com.example.aguavida;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;

public class G_Inflow_Rate extends AppCompatActivity {

    EditText medidoreditText;
    EditText T1editText;
    EditText T2editText;
    EditText T3editText;

    int m;
    int t1;
    int t2;
    int t3;

    public double a;
    public double result;

    public void caudalinput(View view) {

        Context context_caudal = getApplicationContext();
        String exceptionMessage = "";
        String exceptionMessage1 = "";
        String exceptionMessage2 = "";
        String exceptionMessage3 = "";

        try{
            medidoreditText = (EditText) findViewById(R.id.medidoreditText);
            m = Integer.parseInt(medidoreditText.getText().toString());
        } catch (NumberFormatException e) {
            exceptionMessage = "Balde";
        }

        try{
            T1editText = (EditText) findViewById(R.id.t1editText);
            t1 = Integer.parseInt(T1editText.getText().toString());
        } catch (NumberFormatException e) {
            exceptionMessage1 = "time 1";
        }

        try{
            T2editText = (EditText) findViewById(R.id.t2editText);
            t2 = Integer.parseInt(T2editText.getText().toString());
        } catch (NumberFormatException e) {
            exceptionMessage2 = "time 2";
        }

        try{
            T3editText = (EditText) findViewById(R.id.t3editText);
            t3 = Integer.parseInt(T3editText.getText().toString());
        } catch (NumberFormatException e) {
            exceptionMessage3 = "time 3";
        }

        Toast.makeText(this, exceptionMessage + " " + exceptionMessage1 + " " + exceptionMessage2 + "" + exceptionMessage3, Toast.LENGTH_LONG).show();

        a = (t1 + t2 + t3)/3;
        result = m / a;

    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_g__inflow__rate);

        Button gcc_button = (Button) findViewById(R.id.gcc_button);
        gcc_button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                TextView gcc_result_textView = (TextView) findViewById(R.id.g_result_textView);
                gcc_result_textView.setText(result + " ");

            }
        });
    }
}

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".G_Inflow_Rate">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="32dp"
        android:text="Tiempo (en segundos)"
        app:layout_constraintBottom_toTopOf="@+id/t1editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/t2editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="32dp"
        android:ems="10"
        android:hint="tiempo 2 segundos"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/t3editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/t1editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="32dp"
        android:ems="10"
        android:hint="tiempo 1 segundos"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/t2editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/medidoreditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="40dp"
        android:ems="10"
        android:hint="litros"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/t3editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="48dp"
        android:ems="10"
        android:hint="tiempo 3 segundos"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/gcc_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="24dp"
        android:text="Litros del balde/botella"
        app:layout_constraintBottom_toTopOf="@+id/medidoreditText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/gcc_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="64dp"
        android:text="Calcular"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/g_result_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="60dp"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.488"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/button8"
        android:layout_width="423dp"
        android:layout_height="88dp"
        android:text="info"
        tools:layout_editor_absoluteX="-6dp"
        tools:layout_editor_absoluteY="-8dp" />
</android.support.constraint.ConstraintLayout>

Мой код приведен ниже, и на данный момент я люблю некоторые рекомендации о том, как действовать и структурировать это, потому что я на 100% уверен, что я его построил очень неправильно.

Большое спасибо!

1 Ответ

0 голосов
/ 09 ноября 2019

Вы можете избежать проверки только try-catch, если данные EditText пусты или нет, а затем преобразовать их в Integer. Я отправил это для одного EditText. Вы можете сделать это для других

String editor =  medidoreditText.getText().toString();
m = TextUtils.isEmpty(editor) ? 0 : Integer.parseInt(editor);
...