Home > Blockchain >  App crashing when I click on the button saying that I attempt to invoke a method on a null object
App crashing when I click on the button saying that I attempt to invoke a method on a null object

Time:06-21

I am developing an app that needs to register the user, and I am having problems when I started developing some functions to verify if everything is wright, I think that is a problem in the array, but I don't have any idea of how to solve it...

To explain what is going on, basically I started the button and when I click it, it will store all texts in editTexts on array dados, then he will start to verify all the informations, first looking if there is something blank, and then if is a valid username, email, and the same passwords, if everything is wright he will change to next step of register, otherwise an error message will appear and every EditText will be set as "".

XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".CadastroPt1">

    <Button
        android:id="@ id/btnCadastrar"
        android:layout_width="220dp"
        android:layout_height="66dp"
        android:layout_marginTop="108dp"
        android:backgroundTint="@color/laranja"
        android:clickable="false"
        android:text="Cadastre-se"
        android:textSize="18sp"
        app:cornerRadius="35px"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.476"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/constraintLayout3" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@ id/constraintLayout3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/textView4">

        <TextView
            android:id="@ id/textView8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto_regular"
            android:text="Nome completo:"
            android:textSize="18sp"
            app:layout_constraintStart_toStartOf="@ id/txtNome"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@ id/textView11"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:fontFamily="@font/roboto_regular"
            android:text="Senha:"
            android:textSize="18sp"
            app:layout_constraintStart_toStartOf="@ id/txtSenhaCadastro"
            app:layout_constraintTop_toBottomOf="@ id/txtEmailCadastro" />

        <EditText
            android:id="@ id/txtNome"
            android:layout_width="320dp"
            android:layout_height="38sp"

            android:layout_marginTop="10dp"

            android:background="@drawable/custom_input"
            android:ems="10"
            android:hint="Nome"
            android:inputType="textPersonName"
            android:lineSpacingExtra="14sp"
            android:padding="8sp"
            android:textAlignment="textStart"
            app:layout_constraintStart_toStartOf="@ id/textView9"
            app:layout_constraintTop_toBottomOf="@ id/textView8" />

        <EditText
            android:id="@ id/txtConfirmeSenha"
            android:layout_width="320dp"
            android:layout_height="38sp"

            android:layout_marginTop="10dp"
            android:background="@drawable/custom_input"
            android:ems="10"
            android:hint="Confirme sua senha"
            android:inputType="textPassword"
            android:lineSpacingExtra="14sp"
            android:padding="8sp"
            android:textAlignment="textStart"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@ id/textView10" />

        <TextView
            android:id="@ id/textView10"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:fontFamily="@font/roboto_regular"
            android:text="Confirme sua senha:"
            android:textSize="18sp"
            app:layout_constraintStart_toStartOf="@ id/txtConfirmeSenha"
            app:layout_constraintTop_toBottomOf="@ id/txtSenhaCadastro" />

        <TextView
            android:id="@ id/textView9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:fontFamily="@font/roboto_regular"
            android:text="E-mail:"
            android:textSize="18sp"
            app:layout_constraintStart_toStartOf="@ id/txtEmailCadastro"
            app:layout_constraintTop_toBottomOf="@ id/txtNome" />

        <EditText
            android:id="@ id/txtEmailCadastro"
            android:layout_width="320dp"
            android:layout_height="38sp"

            android:layout_marginTop="10dp"

            android:background="@drawable/custom_input"
            android:ems="10"
            android:hint="E-mail"
            android:inputType="textEmailAddress"
            android:lineSpacingExtra="14sp"
            android:padding="8sp"
            android:textAlignment="textStart"
            app:layout_constraintStart_toStartOf="@ id/textView11"
            app:layout_constraintTop_toBottomOf="@ id/textView9" />

        <EditText
            android:id="@ id/txtSenhaCadastro"
            android:layout_width="320dp"
            android:layout_height="38sp"

            android:layout_marginTop="10dp"

            android:background="@drawable/custom_input"
            android:ems="10"
            android:hint="Senha"
            android:inputType="textPassword"
            android:lineSpacingExtra="14sp"
            android:padding="8sp"
            android:textAlignment="textStart"
            app:layout_constraintStart_toStartOf="@ id/textView10"
            app:layout_constraintTop_toBottomOf="@ id/textView11" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <ImageView
        android:id="@ id/imageView3"
        android:layout_width="230sp"
        android:layout_height="80sp"
        android:layout_marginTop="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/logotechtablecolorida" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/constraintLayout3">

        <com.google.android.material.textfield.TextInputLayout
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
            android:layout_width="200dp"
            android:layout_height="65dp"
            android:layout_margin="16dp"
            android:backgroundTint="@color/black"
            android:foregroundTint="@color/laranja"
            android:hint="@string/select"
            app:boxStrokeColor="@color/laranja"
            app:hintTextColor="@color/black"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <AutoCompleteTextView
                android:id="@ id/auto_complete_txt"
                android:layout_width="200dp"
                android:layout_height="55dp"
                android:fontFamily="@font/roboto_regular"
                android:inputType="none"
                android:padding="10sp"
                android:gravity="center_vertical"
                android:textColor="@color/black"
                android:textSize="16sp"
                tools:ignore="TouchTargetSizeCheck" />


        </com.google.android.material.textfield.TextInputLayout>

        <TextView
            android:id="@ id/textView17"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto_regular"
            android:text="Gênero:"
            android:textSize="18sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <TextView
        android:id="@ id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/lgeorge_bold"
        android:text="Cadastre-se"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/imageView3" />

</androidx.constraintlayout.widget.ConstraintLayout>

Activity

package com.example.techtable;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class CadastroPt1 extends AppCompatActivity {
    private Button btnPt2;

    // Objetos para o autocomplete do genero
    String[] generos = {"Masculino", "Feminino", "Outro"};
    AutoCompleteTextView autoCompleteTxt;
    ArrayAdapter<String> adapterItens;

    // Declaração dos inputs
    EditText txtNome;
    EditText txtEmail;
    EditText txtSenhaCadastro;
    EditText txtConfirmeSenha;

    String[] dados = new String[4];
    String genero;


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

        // Instanciamento dos editTexts
        txtNome = (EditText) findViewById(R.id.txtNome);
        txtEmail = (EditText)findViewById(R.id.txtEmail);
        txtSenhaCadastro = (EditText)findViewById(R.id.txtSenhaCadastro);
        txtConfirmeSenha = (EditText)findViewById(R.id.txtConfirmeSenha);

        // Obter gênero do usuario
        autoCompleteTxt = findViewById(R.id.auto_complete_txt);
        adapterItens = new ArrayAdapter<>(this, R.layout.list_item, generos);
        autoCompleteTxt.setAdapter(adapterItens);
        autoCompleteTxt.setOnItemClickListener((parent, view, position, id) -> {
            // String do genero selecionado
            genero = parent.getItemAtPosition(position).toString();
        });

        // Botão para prosseguir
        btnPt2 = findViewById(R.id.btnCadastrar);
        btnPt2.setOnClickListener(view ->{
            // Coleta de dados inseridos:
            dados[0] = txtNome.getText().toString();
            dados[1] = txtEmail.getText().toString();
            dados[2] = txtSenhaCadastro.getText().toString();
            dados[3] = txtConfirmeSenha.getText().toString();
            dados[4] = genero;

            if(verificarInformacoes(dados)) {
                irParaPt2();
            } else{
                // Limpar dados:
                txtNome.setText("");
                txtEmail.setText("");
                txtSenhaCadastro.setText("");
                txtConfirmeSenha.setText("");
            }
        });

    }
    public void irParaPt2(){
        Intent intent = new Intent(this, CadastroPt2.class);
        startActivity(intent);
    }


    public boolean verificarInformacoes(String[] dadosInfo){
        setContentView(R.layout.activity_cadastro_pt1);

        int c = 0;
        boolean verificador = true;
        // Verificar se há dados vázios:
        while (c <= 4){
            if(dadosInfo[c].isEmpty()){
                Toast.makeText(getApplicationContext(), "Preencha todos os espaços!", Toast.LENGTH_LONG).show();
                verificador = false;
            }
            c  ;
        }

        // Verificar formato dos valores:
        // Se houver numeros ou simbolos no nome retorne falso:
        if(!dadosInfo[0].matches("[a-zA-Z] ")){
            Toast.makeText(getApplicationContext(), "Nome inválido!", Toast.LENGTH_LONG).show();
            verificador = false;
        }

        // Se email não for válido ao padrao retorne falso:
        if(!Patterns.EMAIL_ADDRESS.matcher(dadosInfo[1]).matches()){
            Toast.makeText(getApplicationContext(), "Email inválido!", Toast.LENGTH_LONG).show();
            verificador = false;
        }

        // Se senhas não forem iguais retorne falso:
        if(dadosInfo[2].equals(dadosInfo[3])){
            Toast.makeText(getApplicationContext(), "Senhas não batem!", Toast.LENGTH_LONG).show();
            verificador = false;
        }

        // Verificar se algo trocou verificador para false:
        return verificador;
    }
}

LogCat Error

2022-06-20 19:09:54.666 8912-8912/com.example.techtable E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.techtable, PID: 8912
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.techtable.CadastroPt1.lambda$onCreate$1$CadastroPt1(CadastroPt1.java:58)
        at com.example.techtable.-$$Lambda$CadastroPt1$Lpk7Jb4k4tSRL0kGZRZbPTDcMh8.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:8160)
        at android.widget.TextView.performClick(TextView.java:16222)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1131)
        at android.view.View.performClickInternal(View.java:8137)
        at android.view.View.access$3700(View.java:888)
        at android.view.View$PerformClick.run(View.java:30236)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8653)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

CodePudding user response:

There are two errors here. The first is that there is no object named txtEmail. Another is that the length of the dados array is entered incorrectly. Changes you need to make:

txtEmail = (EditText)findViewById(R.id.txtEmailCadastro);

The other is:

String[] dados = new String[5];

Because:

    dados[0] = txtNome.getText().toString();
    dados[1] = txtEmail.getText().toString();
    dados[2] = txtSenhaCadastro.getText().toString();
    dados[3] = txtConfirmeSenha.getText().toString();
    dados[4] = genero;

You used five objects here, not four.

  • Related