Disable button back on android

-1

I have the following problem, I start a Activity to create a user, where it shows me a View dialogLayout at the beginning where a user parameter is entered to validate that it does not already exist, the subject is that if I press the back button, the View dialogLayout is closed and the registration form remains open. I already tried using a onBackPressed but closes only the View dialogLayout , and I need to close all View dialogLayout and Activity

public class CrearCuenta extends AppCompatActivity {

    RelativeLayout crearCuenta;
    Context context;
    Dialog dialog;
    EditText nombre, apellido, dni, fechaNac, direccion, telefono, email;
    Spinner obraSocial, grupoSanguineo;
    ImageView fechaNacDP;
    String [] items;
    int dia, mes, anio, posicion, documento;
    Usuario u;
    Persona p;
    Paciente pa;
    long idOS, id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crear_cuenta);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        context = CrearCuenta.this;
        crearCuenta = (RelativeLayout) findViewById(R.id.registrarUsuario);
        nombre = (EditText) findViewById(R.id.cuentaNombre);
        apellido = (EditText) findViewById(R.id.cuentaApellido);
        dni = (EditText) findViewById(R.id.cuentaDni);
        fechaNac = (EditText) findViewById(R.id.cuentaFechaNac);
        fechaNacDP = (ImageView) findViewById(R.id.cuentaCalFechaNac);
        direccion = (EditText) findViewById(R.id.cuentaDireccion);
        telefono = (EditText) findViewById(R.id.cuentaTelefono);
        email = (EditText) findViewById(R.id.cuentaEmail);
        obraSocial = (Spinner) findViewById(R.id.cuentaSpinnerOS);
        grupoSanguineo = (Spinner) findViewById(R.id.cuentaSpinnerGS);
        pedirDni();
        final ControladorObraSocial controladorOS = new ControladorObraSocial(context);
        controladorOS.cargarSpinnerOS();



        final ArrayAdapter<CharSequence> adaptador = new ArrayAdapter(this, android.R.layout.simple_spinner_item, controladorOS.listaOS);
        obraSocial.setAdapter(adaptador);
        obraSocial.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<ObraSocial> lista;
                lista = controladorOS.listaOS();
                posicion = position;
                if (position > 0) {
                    idOS = (lista.get(posicion - 1).getIdOS());
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        items = getResources().getStringArray(R.array.grupos);
        ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
        grupoSanguineo.setAdapter(ad);
        grupoSanguineo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


        fechaNacDP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar c = Calendar.getInstance();
                dia=c.get(Calendar.DAY_OF_MONTH);
                mes=c.get(Calendar.MONTH);
                anio=c.get(Calendar.YEAR);
                DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener(){
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        fechaNac.setText(dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
                    }
                }, dia,mes,anio);
                datePickerDialog.show();
            }
        });



        crearCuenta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (validarCampos() == true) {
                    LayoutInflater inflater = getLayoutInflater();
                    final View dialogLayout = inflater.inflate(R.layout.dialog_cargar_pass, null);
                    final EditText pass = (EditText) dialogLayout.findViewById(R.id.edtPass);
                    final EditText repass = (EditText) dialogLayout.findViewById(R.id.edtRePass);
                    Button cancelar = (Button) dialogLayout.findViewById(R.id.btnCancelarCrearUsuario);
                    Button aceptar = (Button) dialogLayout.findViewById(R.id.btnCrearUsuario);
                    aceptar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                       StrictMode.setThreadPolicy(policy);
                       ControladorUsuario ctrlUsuario = new ControladorUsuario(context);
                        ControladorPaciente ctrlPaciente = new ControladorPaciente(context);
                        ControladorPersona ctrlPersona = new ControladorPersona(context);
                        id = (ctrlUsuario.getUltimoId()+1);

                        String psw = pass.getText().toString();
                        String rpsw = repass.getText().toString();
                        if (psw.equals(rpsw)) {
                            setUsuario(psw, id);
                            setPersona(id);
                            setPaciente(id);

                            try {
                                ctrlUsuario.agregarUsuario(u);
                                ctrlPersona.agregarPersona(p);
                                ctrlPaciente.agregarPaciente(pa);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                            confirmacion();
                          limpiarcampos();

                        }else {
                            errorPass();
                        }
                    }
                });


                cancelar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setView(dialogLayout);
                dialog = builder.show();

                }
                else {
                    errorCampoIncompleto();
                }


            }
        });


    }


    public void limpiarcampos(){
        nombre.setText("");
        apellido.setText("");
        dni.setText("");
        direccion.setText("");
        telefono.setText("");
        email.setText("");
    }

    public void confirmacion(){
        android.app.AlertDialog.Builder dlgAlert  = new android.app.AlertDialog.Builder(this);
        dlgAlert.setMessage("Se ha agregado exitosamente!");
        dlgAlert.setTitle("Agregar Persona");
        dlgAlert.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent agregar = new Intent(context, Pantalla.class);
                        startActivity(agregar);
                    }
                });
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
    }

    public boolean validarCampos(){
        if (nombre.getText().toString().length() > 0 && apellido.getText().toString().length() > 0 && dni.getText().toString().length() > 0 && direccion.getText().toString().length() > 0 && telefono.getText().toString().length() > 0 && email.getText().toString().length() > 0 ){
            return true;
        }else{
            return false;
        }
    }

    public Usuario setUsuario(String pass, long id) {
        u = new Usuario();
        u.setUsuario(dni.getText().toString());
        u.setPass(pass);
        u.setEstado("Pendiente");
        u.setIdUsuario(id);
        return u;
    }


    public Persona setPersona(long id){
        p = new Persona();
        p.setIdPersona(id);
        p.setNombre(nombre.getText().toString());
        p.setApellido(apellido.getText().toString());
        p.setDni(dni.getText().toString());
        p.setFechaNacimiento(fechaNac.getText().toString());
        p.setDireccion(direccion.getText().toString());
        p.setTelefono(telefono.getText().toString());
        p.setEmail(email.getText().toString());

       return p;
    }

    public Paciente setPaciente(long id){
        pa = new Paciente();
        pa.setIdPaciente(id);
        pa.setIdOS(idOS);
        pa.setGrupoSanguineo(grupoSanguineo.getSelectedItem().toString());
       return pa;
    }

public void pedirDni(){
    LayoutInflater inflater = getLayoutInflater();
    final View dialogLayout = inflater.inflate(R.layout.dialog_pedir_dni, null);
    final EditText dniTxt = (EditText) dialogLayout.findViewById(R.id.pedirDni);
    Button aceptar = (Button) dialogLayout.findViewById(R.id.aceptarPedirDni);
    Button cancelar = (Button) dialogLayout.findViewById(R.id.cancelarPedirDni);



    aceptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ControladorPaciente ctrlPaciente = new ControladorPaciente(context);
            documento = Integer.parseInt(dniTxt.getText().toString());
            boolean existePaciente = ctrlPaciente.validarPaciente(documento);

            if (existePaciente == true){
                Toast.makeText(context, "El DNI ya se encuentra registrado", Toast.LENGTH_LONG).show();

            }else {
                dni.setText(dniTxt.getText().toString());
                dni.setEnabled(false);
                dialog.dismiss();

            }
    }});

    cancelar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setView(dialogLayout);
    dialog = builder.show();

}



    public void errorCampoIncompleto(){
        Toast.makeText(getBaseContext(), "Error, campos sin completar!!", Toast.LENGTH_LONG).show();
    }

    public void errorPass(){
        Toast.makeText(getBaseContext(), "Error!!!, las contraseñas no coinciden", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
        this.finish();
    }

}
    
asked by Germanccho 02.08.2018 в 16:27
source

1 answer

1

You have 2 options since you are using AlertDialog.Builder , one is to disable the physical back button in this way:

AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false);

this makes that your dialog can not be closed either with the back button, or by clicking outside of your dialog.

and in this way you can close the activity and the dialog at the moment you click on the cancel button.

The other option is to add a listener to your dialog to know when to close.

builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { this.finish() // el this es el context de tu actividad. } });

This way, even if the user presses the back button you can close the dialog and your activated at the same time.

I hope my answer will be useful greetings.

    
answered by 02.08.2018 / 17:19
source