Conditional return of Checkbox with problem

Asked

Viewed 138 times

1

I’m making a mistake that ridiculously seems easy, but I can’t fix it.

In my xml has a CheckBox returning false (disabled), in my java has a simple if(termosUso.isChecked()){}, in theory was so that when the CheckBox was returning true(selected), it execute whatever is inside the if or simply continue the program, when I give a Run it runs on the mobile, but the CheckBox does not work, when I debug, the app appears on the console the following error when I click the register button:

ERROR:

E/Androidruntime: FATAL EXCEPTION: main Process: app.conect.medicconect1, PID: 12972 java.lang.Nullpointerexception: Attempt to invoke virtual method 'Boolean android.widget.Checkbox.isChecked()' on a null Object Reference at app.conect.medicconect1.Loginactivity$4.onClick(Loginactivity.java:178) at android.view.View.performClick(View.java:6600) at android.view.View.performClickInternal(View.java:6577) at android.view.View.access$3100(View.java:781) at android.view.View$Performclick.run(View.java:25912) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.Activitythread.main(Activitythread.java:6923) at java.lang.reflect.Method.invoke(Native Method) at com.android.Internal.os.Runtimeinit$Methodandargscaller.run(Runtimeinit.java:493) at com.android.Internal.os.Zygoteinit.main(Zygoteinit.java:870)

XML:

 <CheckBox
            android:id="@+id/termosUso2"
            android:layout_width="314dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:checked="false"
            android:drawableRight="@drawable/icon_termo_uso"
            android:text="Li e Concordo com os Termos de Uso."
            android:textStyle="italic" />

JAVA:

package app.conect.medicconect1;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

public class LoginActivity extends AppCompatActivity {


    protected EditText emaillog, password;//Parte de Login
    protected Button login, cadastreSe, desn;//Tela de Login
    protected TextInputLayout txtInLayoutUsername, txtInLayoutPassword, txtInLayoutRegPassword;//2 telas (LAYOUT)
    protected CheckBox rememberMe;//Tela de Login
    private String HOST = "http://192.168.0.4/LoginApp/";//HOST da pasta do mysql para ter acesso aos arquivos
    protected EditText nomeCad, apelidoCad, emailCad, passwordCad, passwordConfCad;//Parte de cadastro
    protected Button cadastroCad;//Tela de cadastro
    protected CheckBox termosUso;//Tela de cadastro

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

        emaillog = findViewById(R.id.emaillog2);
        password = findViewById(R.id.password2);
        login = findViewById(R.id.login2);
        cadastreSe = findViewById(R.id.cadastreSe2);
        desn = findViewById(R.id.desenvolvedor2);
        termosUso = (CheckBox) findViewById(R.id.termosUso2);
        txtInLayoutUsername = findViewById(R.id.txtInLayoutUsername);
        txtInLayoutPassword = findViewById(R.id.txtInLayoutPassword);
        rememberMe = findViewById(R.id.rememberMe);

        ClickLogin();

        cadastreSe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClickSignUp();
            }
        });
        desn.setOnClickListener(new View.OnClickListener(){...});
    }

    private void ClickLogin() {...}

    private void ClickSignUp() {

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.register, null);
        dialog.setView(dialogView);

        nomeCad = dialogView.findViewById(R.id.nomeCad2);
        apelidoCad = dialogView.findViewById(R.id.apelidoCad2);
        passwordCad = dialogView.findViewById(R.id.passwordCad2);
        passwordConfCad = dialogView.findViewById(R.id.passwordConfCad2);
        emailCad = dialogView.findViewById(R.id.emailCad2);
        cadastroCad = dialogView.findViewById(R.id.cadastroCad2);
        txtInLayoutRegPassword = dialogView.findViewById(R.id.txtInLayoutRegPassword);

        cadastroCad.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                String nome = nomeCad.getText().toString();
                String apelido = apelidoCad.getText().toString();
                String email = emailCad.getText().toString();
                String senha = passwordCad.getText().toString();
                String senhaConf = passwordConfCad.getText().toString();
                String URL = HOST + "cadastrar.php";

                   if (nomeCad.getText().toString().trim().isEmpty())         {
                    nomeCad.setError("Por favor, preencha este campo");
                }  if (passwordCad.getText().toString().trim().isEmpty())     {
                    passwordCad.setError("Por favor, preencha este campo");
                }  if (apelidoCad.getText().toString().trim().isEmpty())      {
                    apelidoCad.setError("Por favor, preencha este campo");
                }  if (emailCad.getText().toString().trim().isEmpty())        {
                    emailCad.setError("Por favor, preencha este campo");
                }  if (passwordConfCad.getText().toString().trim().isEmpty()) {
                    passwordConfCad.setError("Por favor, preencha este campo");
                }

                   if (senhaConf.equals(senha)){
                    if (nome.trim().isEmpty() || apelido.trim().isEmpty() || email.trim().isEmpty() || senha.trim().isEmpty() || senhaConf.trim().isEmpty()) {
                        Toast.makeText(LoginActivity.this, "Por Favor verifique se os campos estão preenchidos corretamente.", Toast.LENGTH_LONG).show();
                    }else {
                        if (termosUso.isChecked()) {//está é a linha 178 no java e aparecentemente a que está errada!

                            Ion.with(LoginActivity.this)
                                    .load(URL)
                                    .setBodyParameter("nome_app", nome)
                                    .setBodyParameter("apelido_app", apelido)
                                    .setBodyParameter("email_app", email)
                                    .setBodyParameter("senha_app", senha)
                                    .asJsonObject()
                                    .setCallback(new FutureCallback<JsonObject>() {
                                        @Override
                                        public void onCompleted(Exception e, JsonObject result) {
                                            try {
                                                //   Toast.makeText(cadastroActivity.this, "Nome: " + result.get("NOME").getAsString(), Toast.LENGTH_LONG).show();
                                                String RETORNO = result.get("CADASTRO").getAsString();

                                                if (RETORNO.equals("EMAIL_ERRO")) {
                                                    Toast.makeText(LoginActivity.this, "Ops! Este email já está cadastrado", Toast.LENGTH_LONG).show();
                                                } else if (RETORNO.equals("SUCESSO")) {
                                                    // Toast.makeText(cadastroActivity.this, "Cadastrado com sucesso", Toast.LENGTH_LONG).show();
                                                    Intent abreHome = new Intent(LoginActivity.this, homeActivity.class);
                                                    startActivity(abreHome);
                                                } else {
                                                    Toast.makeText(LoginActivity.this, "Ops! Ocorreu um erro", Toast.LENGTH_LONG).show();
                                                }
                                            } catch (Exception erro) {
                                                Toast.makeText(LoginActivity.this, "ops! Ocorreu um erro, " + erro, Toast.LENGTH_LONG).show();

                                            }
                                        }
                                    });
                        }else{
                            Toast.makeText(LoginActivity.this, "Para continuar é preciso concordar com os termos de uso!", Toast.LENGTH_LONG).show();
                        }
                    } //fecha else dos camposvazios
                }else {
                    Toast.makeText(LoginActivity.this, "Senhas Diferentes!", Toast.LENGTH_LONG).show();
                       passwordConfCad.setError("Por favor, preencha este campo");
                }
            }
        });
        dialog.show();
    }
}
  • I edited your title for a better understanding

  • Just to have ctz, this Checkbox is in the xml msm of R.layout.activity_login?

  • Yes, Checkbox is in xml msm @Murillocomino

  • @Matheusoliveira unfortunately could not identify any checkbox error

1 answer

0


Apparently I managed to solve this little problem myself.

In Loginactivity I had the main 'Xml' (activity_login.xml), and a 'Diolog' (Register.xml), the problem was that I had associated the 'Checkbox' in the main and not in Register which was where it was created. To solve this just take the...

termosUso = (CheckBox) findViewById(R.id.termosUso2);

onCreate in the login and put it in its proper place, ie within Clicksignup(), and add the 'dialogView. ', in the line of code getting exactly like this...

termosUso = (CheckBox) dialogView.findViewById(R.id.termosUso2);

and the whole code like this.

package app.conect.medicconect1;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

public class LoginActivity extends AppCompatActivity {

protected EditText emaillog, password;//Parte de Login
protected Button login, cadastreSe, desn;//Tela de Login
protected TextInputLayout txtInLayoutUsername, txtInLayoutPassword, txtInLayoutRegPassword;//2 telas (LAYOUT)
protected CheckBox rememberMe;//Tela de Login
private String HOST = "http://192.168.0.4/LoginApp/";//HOST da pasta do mysql para ter acesso aos arquivos
protected EditText nomeCad, apelidoCad, emailCad, passwordCad, 
passwordConfCad;//Parte de cadastro
protected Button cadastroCad, btnUso;//Tela de cadastro
protected CheckBox termosUso;//Tela de cadastro

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

    emaillog = findViewById(R.id.emaillog2);
    password = findViewById(R.id.password2);
    login = findViewById(R.id.login2);
    cadastreSe = findViewById(R.id.cadastreSe2);
    desn = findViewById(R.id.desenvolvedor2);
    txtInLayoutUsername = findViewById(R.id.txtInLayoutUsername);
    txtInLayoutPassword = findViewById(R.id.txtInLayoutPassword);
    rememberMe = findViewById(R.id.rememberMe);

    ClickLogin();

    cadastreSe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ClickSignUp();
        }
    });
    desn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick (View v){

            Intent abreHome = new Intent(LoginActivity.this, homeActivity.class);
            startActivity(abreHome);
        }
    });
}

public void ClickLogin () {...}
public void ClickUso   () {...}
public void ClickSignUp() {

    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    LayoutInflater inflater = getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.register, null);
    dialog.setView(dialogView);

    nomeCad = dialogView.findViewById(R.id.nomeCad2);
    apelidoCad = dialogView.findViewById(R.id.apelidoCad2);
    passwordCad = dialogView.findViewById(R.id.passwordCad2);
    passwordConfCad = dialogView.findViewById(R.id.passwordConfCad2);
    emailCad = dialogView.findViewById(R.id.emailCad2);
    cadastroCad = dialogView.findViewById(R.id.cadastroCad2);
    btnUso = dialogView.findViewById(R.id.btnUso);
    txtInLayoutRegPassword = dialogView.findViewById(R.id.txtInLayoutRegPassword);

    termosUso = (CheckBox) dialogView.findViewById(R.id.termosUso2);

    btnUso.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick (View v){
            ClickUso();
        }
    });
    cadastroCad.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            String nome = nomeCad.getText().toString();
            String apelido = apelidoCad.getText().toString();
            String email = emailCad.getText().toString();
            String senha = passwordCad.getText().toString();
            String senhaConf = passwordConfCad.getText().toString();
            String URL = HOST + "cadastrar.php";


               if (nomeCad.getText().toString().trim().isEmpty())         {
                nomeCad.setError("Por favor, preencha este campo");
            }  if (passwordCad.getText().toString().trim().isEmpty())     {
                passwordCad.setError("Por favor, preencha este campo");
            }  if (apelidoCad.getText().toString().trim().isEmpty())      {
                apelidoCad.setError("Por favor, preencha este campo");
            }  if (emailCad.getText().toString().trim().isEmpty())        {
                emailCad.setError("Por favor, preencha este campo");
            }  if (passwordConfCad.getText().toString().trim().isEmpty()) {
                passwordConfCad.setError("Por favor, preencha este campo");
            }

               if (senhaConf.equals(senha)){
                if (nome.trim().isEmpty() || apelido.trim().isEmpty() || email.trim().isEmpty() || senha.trim().isEmpty() || senhaConf.trim().isEmpty()) {
                    Toast.makeText(LoginActivity.this, "Por Favor verifique se os campos estão preenchidos corretamente.", Toast.LENGTH_LONG).show();
                }else {
                    if (termosUso.isChecked()) {

                        Ion.with(LoginActivity.this)
                                .load(URL)
                                .setBodyParameter("nome_app", nome)
                                .setBodyParameter("apelido_app", apelido)
                                .setBodyParameter("email_app", email)
                                .setBodyParameter("senha_app", senha)
                                .asJsonObject()
                                .setCallback(new FutureCallback<JsonObject>() {
                                    @Override
                                    public void onCompleted(Exception e, JsonObject result) {
                                        try {
                                            //   Toast.makeText(cadastroActivity.this, "Nome: " + result.get("NOME").getAsString(), Toast.LENGTH_LONG).show();
                                            String RETORNO = result.get("CADASTRO").getAsString();

                                            if (RETORNO.equals("EMAIL_ERRO")) {
                                                Toast.makeText(LoginActivity.this, "Ops! Este email já está cadastrado", Toast.LENGTH_LONG).show();
                                            } else if (RETORNO.equals("SUCESSO")) {
                                                // Toast.makeText(cadastroActivity.this, "Cadastrado com sucesso", Toast.LENGTH_LONG).show();
                                                Intent abreHome = new Intent(LoginActivity.this, homeActivity.class);
                                                startActivity(abreHome);
                                            } else {
                                                Toast.makeText(LoginActivity.this, "Ops! Ocorreu um erro", Toast.LENGTH_LONG).show();
                                            }
                                        } catch (Exception erro) {
                                            Toast.makeText(LoginActivity.this, "ops! Ocorreu um erro, " + erro, Toast.LENGTH_LONG).show();

                                        }
                                    }
                                });
                    }else{
                        Toast.makeText(LoginActivity.this, "Para continuar é preciso concordar com os termos de uso!", Toast.LENGTH_LONG).show();
                    }
                } //fecha else dos campos preenchidos
            }else {
                Toast.makeText(LoginActivity.this, "Senhas Diferentes!", Toast.LENGTH_LONG).show();
                   passwordConfCad.setError("Por favor, preencha este campo");
            }
        }
    });
    dialog.show();
  }
}

In short, I called an item in a place where it didn’t exist.

Browser other questions tagged

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