The application for when editText is not populated

Asked

Viewed 101 times

1

Hello! I’d like to ask for your help. I’m new to Android studio and I’m trying to create an app for my physics students to calculate motion equations. One of the methods is to calculate the equation "V=v0+at", when editTexts are filled works normal, but when one becomes empty the application stops. I have tried several ways to use methods that identify empty variables but never work.

Follow the code below:

public void velocidadeTempo(View view){
    setContentView(R.layout.velocidade_tempo);

    final EditText editV0 = findViewById(R.id.editv0);
    final EditText editA = findViewById(R.id.edita);
    final EditText editT = findViewById(R.id.editt);

    final TextView tvV1 = findViewById(R.id.tvResultado);


    final double[] velocidadeF = new double[1];

    Button btcalcular = findViewById(R.id.btCalcular);

    btcalcular.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String numv0 = editV0.getText().toString();
            double v0 = Double.parseDouble(numv0);

            String numa = editA.getText().toString();
            double a = Double.parseDouble(numa);

            String numt = editT.getText().toString();
            double t = Double.parseDouble(numt);

            velocidadeF[0] = v0 + (a*t);

            if(editV0.getText().toString().isEmpty()||editA.getText().toString().isEmpty()||editT.getText().toString().isEmpty()){
                tvV1.setText("sem resposta");
            }else{
                tvV1.setText(velocidadeF[0]+"");
            }

        }
    });
}

Recalling that the value "0" is valid in the equation.

2 answers

1

When the content of an Edittext is used in a mathematical operation it is necessary to ensure at least that:

  • is not null

    if(editText.getText().toString().isEmpty()){
        // O conteúdo é nulo
    }
    
  • represents a numerical value

    <EditText
       android:id="@+id/edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="0" 
       android:inputType="number"/>
    

    The attribute android:text="0" sets zero as default value.
    The attribute android:inputType="number" makes only integer values accepted by Edittext.

These validations have to be made before conversion(parse) content(String) for the corresponding numerical value.

Further validations may be required depending on the type of calculation to be performed.

0

I used this here, modify your code and see if it works

if(!email.getText().toString().isEmpty() && !senha.getText().toString().isEmpty())
   validarLogin();
else
   Toast.makeText(LoginActivity.this, "Um ou mais campos estão vazios", Toast.LENGTH_SHORT).show();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.