What is the way to work with a JSONArray to fill a table with a database?

1

I am using a JSONArray object in an Android application to dynamically fill a table with the information obtained in the query. The problem is that until now I was working with a JSONObject, with which the table was filled, but it was only with the last query obtained, so it did not work for the application to work optimally.

The code that I have improvised to obtain the query, at least to begin to make tests is the following (Edited according to the answer of Pablo Simon DiEstefano):

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(), "Año" + comprobarFecha[0] + "Mes" + comprobarFecha[1] + "Dia" + comprobarFecha[2], 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);

With this code the application gives me an error, although it is not a programming error. When starting what I should theoretically have to give are two tables, one after the other, for each result of the query. However, the first time I hit a date, I get the following

That which comes out is the table corresponding to the second query, and an extra header. However, when I press the date again a second time, I get the following:

It is not very appreciated by the size of the device, but at that moment I get the first result (the first table together with the header) plus a table with the first result, the second and again a header

Any idea how this could be solved?

This is the result of my JSON

[
    {
        "us_usuario": "DONATE",
        "us_clave": "DONATE",
        "hora_inicio": "18:20",
        "hora_fin": "18:35",
        "fecha": "2017-10-29",
        "nombre": "JUAN MANUEL",
        "apellidos": "LLORENTE RODRIGO",
        "prestacion": "REVISION OFTALMOLOGICA"
    },
    {
        "us_usuario": "DONATE",
        "us_clave": "DONATE",
        "hora_inicio": "14:00",
        "hora_fin": "14:15",
        "fecha": "2017-10-29",
        "nombre": "JACINTO",
        "apellidos": "JARAMILLO ROMERO",
        "prestacion": "FOTOCOAGULACION DR"
    }
]
    
asked by G. Corporales 03.11.2017 в 10:11
source

1 answer

2

I think the error comes from this line:

String [] arrayRespuesta = new String[jsonArray.length()-3];

If you notice, jsonArray is of length 2:

jsonArray[0] = {
    "us_usuario": "DONATE",
    "us_clave": "DONATE",
    "hora_inicio": "18:20",
    "hora_fin": "18:35",
    "fecha": "2017-10-29",
    "nombre": "JUAN MANUEL",
    "apellidos": "LLORENTE RODRIGO",
    "prestacion": "REVISION OFTALMOLOGICA"
}

jsonArray[1] = {
    "us_usuario": "DONATE",
    "us_clave": "DONATE",
    "hora_inicio": "14:00",
    "hora_fin": "14:15",
    "fecha": "2017-10-29",
    "nombre": "JACINTO",
    "apellidos": "JARAMILLO ROMERO",
    "prestacion": "FOTOCOAGULACION DR"
}

With which, when doing:

String [] arrayRespuesta = new String[jsonArray.length()-3];

You are making an array of -1 positions, which is not correct.

To obtain the data you can do it in the following way:

Response.Listener<String> responseListener = new Response.Listener<String>(){
            @Override
            public void onResponse(String response){
                try{
                    String hora_inicio="", hora_fin="", fecha="", nombre="", apellidos="", prestacion="";
                    JSONArray jsonArray = new JSONArray(response);
                    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);

                    if (comprobarFecha[0] == calendario.getYear() && comprobarFecha[1] == calendario.getMonth()+1 && comprobarFecha[2] == calendario.getDayOfMonth()){
                            tablePaciente.removeAllViews();
                            TablaPacientes tabla = new TablaPacientes(Usuario.this, tablePaciente);
                            cargarTabla(tabla, arrayRespuesta);
                        } else {
                            tablePaciente.removeAllViews();
                            Toast t = Toast.makeText(getApplicationContext(), "Año"+comprobarFecha[0]+"Mes"+comprobarFecha[1]+"Dia"+comprobarFecha[2], Toast.LENGTH_LONG);
                            t.show();
                        }
                    }  //El for lo acabamos aquí para que en cada iteración meta un elemento
                }catch(JSONException e){
                    tablePaciente.removeAllViews();
                    Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
                    t.show();
                }catch(ArrayIndexOutOfBoundsException e){
                    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);
    
answered by 03.11.2017 / 10:23
source