Problem Android studio with Object Json

1

I have a problem with my Android Studio code. My application is based on a date selector in which when you select a date it will fill a table with a query with the database and fill in a table with the results obtained. The code of my onCreate method is the following. (Edited according to the answer of A.Cedano)

calendario.init(0, 0, 0, new DatePicker.OnDateChangedListener(){
        @Override
        public void onDateChanged (DatePicker datePicker, int año, int mes, int dia){
            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();
            Response.Listener<String> responseListener = new Response.Listener<String>(){
                @Override
                public void onResponse(String response){
                    try{
                        JSONObject jsonObject = new JSONObject(response);

                        String hora_inicio = jsonObject.getString("hora_inicio");
                        String hora_fin = jsonObject.getString("hora_fin");
                        String fecha = jsonObject.getString("fecha");
                        String nombre = jsonObject.getString("nombre");
                        String apellidos = jsonObject.getString("apellidos");
                        String prestacion = jsonObject.getString("prestacion");

                        int[] comprobarFecha = separarFecha(fecha);
                        String [] arrayRespuesta = {hora_inicio, hora_fin, fecha, nombre, apellidos, prestacion};
                        if (comprobarFecha[0] == calendario.getYear() && comprobarFecha[1] == calendario.getMonth() && comprobarFecha[2] == calendario.getDayOfMonth()){
                                tablePaciente.removeAllViews();
                                TablaPacientes tabla = new TablaPacientes(Usuario.this, tablePaciente);
                                cargarTabla(tabla, arrayRespuesta);
                            } else {
                                Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
                                t.show();
                            }

                    }catch(JSONException e){
                        AlertDialog.Builder builder = new AlertDialog.Builder(Usuario.this);
                        builder.setMessage("Excepción en el JSON "+e.getMessage())
                                .setNegativeButton("Retry", null)
                                .create().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();
                    }
                }
            };
            String fecha = Año+"-"+Mes+"-"+Dia;
            RegisterRequest registerRequest = new RegisterRequest(username, password, fecha, responseListener);
            RequestQueue queue = Volley.newRequestQueue(Usuario.this);
            queue.add(registerRequest);
        }
    });

The error that I get when this activity opens is as follows:

Any idea why it can be? This code is tested in another activity and it works, but this is the first time I try to put it in an onDateChanged

This is the result of my json for user DONATE, key DONATE and date "2017-10-26":

{
    "success": true,
    "hora_inicio": "14:00",
    "hora_fin": "14:15",
    "fecha": "2017-10-26",
    "nombre": "JUAN MANUEL",
    "apellidos": "LLORENTE RODRIGO",
    "prestacion": "REVISION OFTALMOLOGICA"
}

And this is the php code of my application:

Any possible solution, please? In the json it is clearly seen that hora_enicio if it gives an answer, but nevertheless does not seem to pick it up. Why could it be?

    
asked by G. Corporales 27.10.2017 в 09:35
source

1 answer

2

If the JSON returns it to you as you have it in the question, this is a JSONObject , not before a JSONArray .

Then:

  • You should create a JSONObject from response and not a JSONArray .

  • You will not need the for if it is a single JSON object. If there are several you will use the for, but counting the values of the JSONObject , not the JSONArray .

  • In the JSON you show the values are not organized as you try to read them. For example, the name does not come in a key called nombre but the name key is called 4 . It means that this will not work: String nombre = jsonObject.getString("nombre"); for the name. Instead this yes: String nombre = jsonObject.getString("4"); . The same goes for the other values. And also, hora_inicio and other relatives do not come in an array ... I do not know why you try to read them like this:

                        arrayRespuesta[0] = hora_inicio;
                        arrayRespuesta[1] = hora_fin;
                        arrayRespuesta[2] = fecha;
                        arrayRespuesta[3] = nombre;
                        arrayRespuesta[4] = apellidos;
                        arrayRespuesta[5] = prestacion;
    
  • when those values come as flat keys in the JSON.

    It is clear that the construction of your JSON is not being done properly.

    Anyway, a corrected code (for the JSON as you have it now) would be:

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        //String [] arrayRespuesta = new String [results.length()];
    
                            String hora_inicio = jsonObject.getString("1");
                            String hora_fin = jsonObject.getString("2");
                            String fecha = jsonObject.getString("3");
                            String nombre = jsonObject.getString("4");
                            String apellidos = jsonObject.getString("5");
                            String prestacion = jsonObject.getString("6");
    
    
                        //no hay aquí } de cierre del for
    

    The assumed value of arrayRespuesta[2] would actually be obtained like this:

                            String fechaArray = jsonObject.getString("fecha");
    
    
    
                        int[] comprobarFecha = separarFecha(fechaArray);
    
                        //... resto del código
    

    Making those changes the code will work if there are no other errors. But it is not desirable. I think you should check the JSON at the source to be built with descriptive key names and not numbers.

        
    answered by 28.10.2017 / 00:43
    source