3 votes

Android application malfunction

I have an application in Android Studio for connection to a database. The application is based on selecting a date in a DatePicker and, if on that date there are patients, filling a table with their data. The application works, and the table is filled, but only if I press the date 2 times. I mean, in theory the table has to be filled as soon as the date is clicked, but in the first click it is only filled with one line and the header of the next one, while if you click twice then it is filled well.

Here is the first keystroke (not very good due to the size of the device) introducir la descripción de la imagen aquí

And here the second keystroke is shown. introducir la descripción de la imagen aquí

My code to populate the application is as follows:

@Override
public void onDateChanged(DatePicker view, int year, int month, int day){
    String username = i.getStringExtra("us_usuario");
    String password = i.getStringExtra("us_clave");
    int Año = calendario.getYear();
    int Mes = calendario.getMonth()+1;
    int Dia = calendario.getDayOfMonth();
    String fecha = Año+"-"+Mes+"-"+Dia;
    Response.Listener<String> responseListener = new Response.Listener<String>(){
        @Override
        public void onResponse(String response){
            try {
                JSONArray jsonArray = new JSONArray(response);
                String hora_inicio, hora_fin, fecha, nombre, apellidos, prestacion;
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    hora_inicio = jsonObject.getString("hora_inicio");
                    hora_fin = jsonObject.getString("hora_fin");
                    fecha = jsonObject.getString("fecha");
                    nombre = jsonObject.getString("nombre");
                    apellidos = jsonObject.getString("apellidos");
                    prestacion = jsonObject.getString("prestacion");

                    String[] arrayRespuesta = {hora_inicio, hora_fin, nombre, apellidos, prestacion};

                    int[] comprobarFecha = separarFecha(fecha);
                    TablaPacientes tabla = new TablaPacientes(Usuario.this, tablePaciente);
                    if(comprobarFecha[0] == calendario.getYear() && comprobarFecha[1] == calendario.getMonth()+1 && comprobarFecha[2] == calendario.getDayOfMonth()){
                       //tablePaciente.removeAllViews();
                        tabla.agregarCabecera(R.array.tabla_pacientes);
                        cargarTabla(tabla, arrayRespuesta);
                    }else{
                        tablePaciente.removeAllViews();
                        Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
                        t.show();
                    }
                }
            }catch(JSONException e){
                tablePaciente.removeAllViews();
                Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
                t.show();
            }catch(ArrayIndexOutOfBoundsException e){
                tablePaciente.removeAllViews();
                AlertDialog.Builder builder = new AlertDialog.Builder(Usuario.this);
                builder.setMessage("Error de excepción en el array "+e.getLocalizedMessage())
                        .setNegativeButton("Retry", null)
                        .create().show();
            }
        }
    };
    RegisterRequest registerRequest = new RegisterRequest(username, password, fecha, responseListener);
    RequestQueue queue = Volley.newRequestQueue(Usuario.this);
    queue.add(registerRequest);
}

Here is my loadTable method:

public void cargarTabla(TablaPacientes tabla, String[] array){
    ArrayList<String> elementos = new ArrayList<>();
    elementos.add(array[0]);//horario
    elementos.add(array[2]);//Nombre
    elementos.add(array[3]);//Apellidos
    elementos.add(array[4]);//Tipo Servicio
    tabla.agregarFilaTabla(elementos);
}

And here my method addTableStack:

public void agregarFilaTabla(ArrayList<String> elementos){
    TableRow.LayoutParams layoutCelda;
    TableRow.LayoutParams layoutFila = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
    TableRow fila = new TableRow(actividad);
    fila.setLayoutParams(layoutFila);
    for(int i = 0; i< elementos.size(); i++){
        TextView texto = new TextView(actividad);
        texto.setText(String.valueOf(elementos.get(i)));
        texto.setGravity(Gravity.START);
        layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(texto.getText().toString()), TableRow.LayoutParams.WRAP_CONTENT);
        texto.setLayoutParams(layoutCelda);
        fila.addView(texto);
    }
    tabla.addView(fila);
    filas.add(fila);
    FILAS++;
}

I know that in the line tablePatient.removeAllViews(); deletes my table, that is, if I have it there it will only show me the second query (if any), but in theory if I remove that line the code should go 2 times through the if to fill the table, putting the 2 queries (or whatever they are). Any idea how to fix it?

2voto

A. Cedano Points 48884

It seems to me that your code has several logic errors.

If I understood correctly, you were trying to pass to a table the values when the date is equal.

In my proposal I have taken all the logic of the table construction out of the loop that reads the JSON. I also do not fill arrayRespuesta always, but only when the condition is met.

Out of the loop, I evaluate whether arrayRespuesta is not empty and then I fill the table. If the array is empty then I display a message in the toaster.

I have not tested it, if I have made a mistake the compiler will tell you.

I hope you find it useful.

@Override
public void onDateChanged(DatePicker view, int year, int month, int day){
    String username = i.getStringExtra("us_usuario");
    String password = i.getStringExtra("us_clave");
    int Año = calendario.getYear();
    int Mes = calendario.getMonth()+1;
    int Dia = calendario.getDayOfMonth();
    String fecha = Año+"-"+Mes+"-"+Dia;
    Response.Listener<String> responseListener = new Response.Listener<String>(){
        @Override
        public void onResponse(String response){

           ArrayList<String> arrayRespuesta = new ArrayList<String>();

            try {
                JSONArray jsonArray = new JSONArray(response);
                String hora_inicio, hora_fin, fecha, nombre, apellidos, prestacion;
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    hora_inicio = jsonObject.getString("hora_inicio");
                    hora_fin = jsonObject.getString("hora_fin");
                    fecha = jsonObject.getString("fecha");
                    nombre = jsonObject.getString("nombre");
                    apellidos = jsonObject.getString("apellidos");
                    prestacion = jsonObject.getString("prestacion");

                    int[] comprobarFecha = separarFecha(fecha);
                    if(comprobarFecha[0] == calendario.getYear() && comprobarFecha[1] == calendario.getMonth()+1 && comprobarFecha[2] == calendario.getDayOfMonth()){
                        arrayRespuesta.add(hora_inicio);
                        arrayRespuesta.add(hora_fin);
                        arrayRespuesta.add(nombre);
                        arrayRespuesta.add(apellidos);
                        arrayRespuesta.add(prestacion);
                    }

                }
            }catch(JSONException e){
                tablePaciente.removeAllViews();
                Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
                t.show();
            }catch(ArrayIndexOutOfBoundsException e){
                tablePaciente.removeAllViews();
                AlertDialog.Builder builder = new AlertDialog.Builder(Usuario.this);
                builder.setMessage("Error de excepción en el array "+e.getLocalizedMessage())
                        .setNegativeButton("Retry", null)
                        .create().show();
            }

            if(!arrayRespuesta.isEmpty()){
                TablaPacientes tabla = new TablaPacientes(Usuario.this, tablePaciente);
                        tabla.agregarCabecera(R.array.tabla_pacientes);
                        cargarTabla(tabla, arrayRespuesta);
            }else{
                Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
                t.show();
            }

        }
    };
    RegisterRequest registerRequest = new RegisterRequest(username, password, fecha, responseListener);
    RequestQueue queue = Volley.newRequestQueue(Usuario.this);
    queue.add(registerRequest);
}

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X