My TimePickerDialog and DatePickerDialog do not modify my EditText when I edit the person (Sqlite)

0

I have a clase that I use to add and edit people in my ListView with Sqlite , when I add a person my editTextFecha I edit it with TimePickerDialog and DatePickerDialog and it works perfectly, but when I edit the person my editTextFecha is only updated if I change it manually (with the keyboard), if I use TimePickerDialog and DatePickerDialog does not send anything to EditTexFecha What could this error be?

* I put a GIF of the problem, as you can see when I add the person is edited correctly, but when I edit it, not

This works perfectly when I add a person:

  final Calendar calendario = Calendar.getInstance();
    dia = calendario.get(Calendar.DAY_OF_MONTH);
    mes = calendario.get(Calendar.MONTH);
    ano = calendario.get(Calendar.YEAR);
    hora = calendario.get(Calendar.HOUR_OF_DAY);
    minutos = calendario.get(Calendar.MINUTE);
    mostrarFecha();
    selectorFecha = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            dia = dayOfMonth;
            mes = month;
            ano = year;
            age.setDateOfBirth(ano, mes, dia);
            calculateAge();
            mostrarFecha();
            mostrarHora();
        }
    };

}

private void mostrarHora() {
    TimePickerDialog timePickerDialog = new TimePickerDialog(this,
            new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay,
                                      int minute) {
                    hora = hourOfDay;
                    minutos = minute;
                    mostrarFecha();

                }
            }, hora, minutos, true);
    timePickerDialog.show();
}

private void calculateAge() {
    age.calcualteYear();
    age.calcualteMonth();
    age.calcualteDay();
    String[] dayMonthYear = age.getResult().split(":");
    String year = dayMonthYear[2];
    editTextEdad.setText(getResources().getString(R.string.edad_actual)
+ " " + year + " " + (getResources().getString(R.string.age)));

}


@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case 0:
            return new DatePickerDialog(this, selectorFecha, ano, mes, dia);
    }
    return null;
}

public void mostrarCalendario(View control) {
    showDialog(TIPO_DIALOGO);
}


public void mostrarFecha() {
    editTextFecha.setText (dia + "/" + (mes + 1) 
+ "/" + ano + " " + hora + ":" + String.format("%02d", minutos));
}

But when I edit the person, I can only edit my editTextFecha manually (with the keyboard) and not with TimePickerDialog and DatePickerDialog because it does not send anything

private void editarPersona() {
    baseDatos = new DatabaseHandler(EditarPersonaActivity.this);

    try {
        int id = extras.getInt("id");
        Persona persona = new Persona(id, editTextFecha.getText()
                .toString());

        baseDatos.actualizarRegistros(id, persona.getFecha());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        baseDatos.cerrar();
    }
}

Method actualizarRegistros of DatabaseHandler

 public void actualizarRegistros(int id, String fecha){
        ContentValues actualizarDatos = new ContentValues();
        actualizarDatos.put("fecha", fecha);
        String where = "_id=?";
        String[] whereArgs = new String[] {String.valueOf(id)};
        try{
            this.getReadableDatabase().update("Personas", actualizarDatos, where, whereArgs);
        }
        catch (Exception e){
            String error =  e.getMessage().toString();
        }
    }

If you need to put the% full% or other information, please notify.

    
asked by UserNameYo 17.02.2017 в 18:07
source

1 answer

1

Final EDIT, I hope

    public class EditarPersonaActivity extends Activity {
        // Objetos.
        private Button butonGuardar;
        private EditText editTextFecha;
        private DatabaseHandler baseDatos;
        private Bundle extras;
        private int dia, mes, ano, hora, minutos;
        private static final int TIPO_DIALOGO = 0;
        private static DatePickerDialog.OnDateSetListener selectorFecha;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.editar_persona);
            butonGuardar = (Button) findViewById(R.id.botonGuardar);
            editTextFecha = (EditText) findViewById(R.id.editTextFecha);

            final Calendar calendario = Calendar.getInstance();
            dia = calendario.get(Calendar.DAY_OF_MONTH);
            mes = calendario.get(Calendar.MONTH);
            ano = calendario.get(Calendar.YEAR);
            hora = calendario.get(Calendar.HOUR_OF_DAY);
            minutos = calendario.get(Calendar.MINUTE);
            selectorFecha = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    dia = dayOfMonth;
                    mes = month;
                    ano = year;
                    mostrarHora();
System.out.println("mostrarHora desde onDateSet");

                }
            };

        }

        private void mostrarHora() {
            TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                    new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay,
                                              int minute) {
                            hora = hourOfDay;
                            minutos = minute;
                            mostrarFecha();

System.out.println("mostrarFecha desde onTimeSet");


                        }
                    }, hora, minutos, true);
            timePickerDialog.show();
        }


        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
                case 0:
                    return new DatePickerDialog(this, selectorFecha, ano, mes, dia);
            }
            return null;
        }

        public void mostrarCalendario(View control) {
            showDialog(TIPO_DIALOGO);
        }

        public void mostrarFecha() {
System.out.println("Llamaste a mostrarFecha");

            editTextFecha.setText(dia + "/" + (mes + 1) + "/" + ano + " " + hora + ":" + String.format("%02d", minutos)
            );


            // Recupera en un Objeto Bundle si tiene valores que fueron pasados como
            // parametro de una actividad.

         extras = getIntent().getExtras();

//Lo sacaste del if pero no lo pusiste aquí:
                editarPersona();

         if (estadoEditarPersona()) {
                editTextFecha.setText(extras.getString("fecha"));


    //// lo saco como me comentas            editarPersona();


            }

            butonGuardar.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if (verificarCampoFecha()) {
                        if (estadoEditarPersona()) {
                            editarPersona();
                        } else {
                            insertarNuevoPersona();
                        }
                        finish();
                    } else {
                        if (editTextFecha.getText().toString().equals("")) {
                        }
                    }
                }
            });
        }

        private boolean verificarCampoFecha() {
            if (editTextFecha.getText().toString().equals("")) {
                return false;
            }
            return true;
        }

    ////////////////// Metodo privado que insertar una nueva Persona.

        private void insertarNuevoPersona() {
            baseDatos = new DatabaseHandler(EditarPersonaActivity.this);

            try {
    ///////////////// Crear objeto de la persona
                Persona persona = new Persona(editTextFecha.getText().toString());
    ////////////////// se inserta una nueva persona
                baseDatos.insertarPersona(persona);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                baseDatos.cerrar();
            }
        }

    ///////////////////////////////// metodo privado para editar una persona existente

        private void editarPersona() {
System.out.println("Llamaste a mostrarFecha");
            baseDatos = new DatabaseHandler(EditarPersonaActivity.this);

//Esto había que comentarlo
//            mostrarFecha();

            try {
    ///////////////// crear objeto persona
                int id = extras.getInt("id");
                Persona persona = new Persona(id, editTextFecha.getText()
                        .toString());

                baseDatos.actualizarRegistros(id, persona.getFecha());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                baseDatos.cerrar();
            }
        }

        public boolean estadoEditarPersona() {
            if (extras != null) {
                return true;
            } else {
                return false;
            }
        }

    }

Updated after seeing a more general view of the code

Test to: As I understand it, you want to, when selecting the time, update it without pressing the button . It is right? Seeing that, after selecting the time you call the mostrarFechaEnvia() method, you would have to update the person by calling the method that does that action. Then, call the method editarPersona() from the method mostrarFechaEnvia() of the class EditarPersonaActivity :

public void mostrarFechaEnvia() {
    editTextFecha.setText(dia + "/" + (mes + 1) + "/" + ano + " " + hora + ":" + String.format("%02d", minutos));


    extras = getIntent().getExtras();


    if (estadoEditarPersona()) {
        editTextFecha.setText(extras.getString("fecha"));
//agregar
    editarPersona();

    }

Updated

a. Update the record when choosing a time in the TimePicker (it's what you need according to what you have stated):

private void mostrarHora() {
    TimePickerDialog timePickerDialog = new TimePickerDialog(this,
            new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay,
                                      int minute) {
                    hora = hourOfDay;
                    minutos = minute;

//Actualizas una vez has elegido la hora
         baseDatos.actualizarRegistros(id, persona.getFecha());

                    mostrarFecha();

                }
            }, hora, minutos, true);
    timePickerDialog.show();
}
//    ... lo que sigue del código

b. Another possibility, if accepting was a button and you want the record to be updated, you just have to add a listener (if it does not exist) to that button and call the method (it does not apply in your case as you stated in a comment, but I leave in case it is useful to someone):

baseDatos.actualizarRegistros(id, persona.getFecha());

Example:

 final Button btnAceptar = (Button) findViewById(R.id.btnaceptar);
 btnAceptar.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
         baseDatos.actualizarRegistros(id, persona.getFecha());
     }
 });

Of course, your DatabaseHandler class must be instantiated from where you call the actualizarRegistros method and in this case your button in the XML is called btnaceptar .

Another possibility would be to call the actualizarRegistros method immediately after having selected a time, in the listener onTimeSet , but this would not give you the possibility to be sure that it is the time you want and confirm it by clicking on accept.

    
answered by 20.02.2017 / 01:13
source