0

espero me puedan ayudar, error esta en " th.nombre as 'th_nombre' " de la sentencia SQL, en el PHP muestra correcto, pero cuando lo quiero mostrar en el aplicativo me salta este error JSONException; pero si en el aplicativo omito la línea referente a " th.nombre as 'th_nombre' " , los datos si se muestran correctamente.

CODIGO PHP:

<?php
include '../conexion.php';
$numero_habitacion=$_GET['numero_habitacion'];

$consulta="SELECT numero_habitacion,th.nombre as 'th_nombre',imagen_habitacion,imagen_habitacion_bano,cantidad_personas_habitacion,terma,ducha,lampara,mesa_de_noche,
ropero,cantidad_camas_total,tipo_cama1,tipo_cama_2,tipo_cama_3,cantidad_TC1,cantidad_TC2,cantidad_TC3,sillas,tvycable,telefono,wifi,
vista_calle,estado_habitacion FROM habitacion h left join tipo_habitacion th on h.tp_habitacion = th.id_tipohabitacion where numero_habitacion ='$numero_habitacion'";

$resultado = $conexion-> query($consulta);

while ($fila=$resultado->fetch_array()){
    $datos[]= array_map(`utf8_encode`,$fila);
}

echo json_encode($datos);
$resultado -> close(); 
?>

CODIGO EN ANDROID PARA MOSTRAR (omito líneas de código, que son de los demás datos a mostrar): LINEA DEL ERROR: textViewTH.setText(jsonObject.getString("th_nombre"));

private void MostrarHabitacion(String URL){
    JsonArrayRequest jsonArrayRequest= new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            JSONObject jsonObject = null;
            for (int i = 0; i < response.length(); i++) {
                try {
                    jsonObject = response.getJSONObject(i);

                    textViewNH.setText(jsonObject.getString("numero_habitacion"));
                    textViewTH.setText(jsonObject.getString("th_nombre"));
                    textViewNP.setText(jsonObject.getString("cantidad_personas_habitacion"));

                } catch (JSONException e) {
                    LayoutInflater inflater = getLayoutInflater();
                    View layout = inflater.inflate(R.layout.activity_mini_mensaje, (ViewGroup) findViewById(R.id.miniContenedor));
                    TextView text = (TextView) layout.findViewById(R.id.tvMensaje);
                    text.setText("ERROR del JSONException");
                    Toast toast = new Toast(getApplicationContext());
                    toast.setDuration(Toast.LENGTH_LONG);
                    toast.setView(layout);
                    toast.show();
                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), error.getMessage() ,Toast.LENGTH_LONG).show();
        }
    }
    );
    requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

1 respuesta 1

0

El problema JSONException que se genera en la línea de código:

textViewTH.setText(jsonObject.getString("th_nombre"));

puede indicar que el valor del campo nombre en tu tabla tipo_habitacion en algunos casos probablemente no existe, ya que se lanza JSONException si no existe el valor o si existe la propiedad para la clave, pero su valor es null.

Para evitar este problema, puedes definir un valor predeterminado como segundo parámetro en estos casos, por ejemplo una cadena vacía en caso de no existir el valor:

textViewTH.setText(jsonObject.getString("th_nombre", ""));

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.