0

I'm learning to use volley, currently making a login and a register form, using a MySQL database and PHP files. I can get the data sent from a POST request sending a JSON object containing the data, actually the data is inserted correctly in the database. I use the next PHP code for it.

<?php

try {

    // Incluímos archivo de la conexión a base de datos
    include 'database.php';

    // Tomando los datos enviados por json
    $json = file_get_contents('php://input');
    // Pasando a php
    $data = json_decode($json, JSON_UNESCAPED_UNICODE);

    // Obtenemos los datos enviados por POST
    $nombre = $data['nombre'];
    $apellido = $data['apellido'];
    $correo = $data['correo'];
    $contrasenia = $data['contrasenia'];
    $telefono = $data['telefono'];

    // Código para buscar si el email está en uso
    $sqlCorreoEnUso = "SELECT id FROM usuarios WHERE correo = '{$correo}'";

    // Comprobando
    $consultaCorreo = mysqli_query($cn, $sqlCorreoEnUso);
    if (mysqli_num_rows($consultaCorreo)){
        echo json_encode([
            'respuesta' => 'error',
            'razon' => 'EmailEnUso'
        ]);
        exit;
    }
    
    // Código SQL para la consulta de inserción
    $sqlInsertarUsuario = "INSERT INTO usuarios(nombre, apellido, correo, contrasenia, telefono) VALUES ('{$nombre}','{$apellido}','{$correo}','{$contrasenia}','{$telefono}')";

    // Realizando
    if (mysqli_query($cn, $sqlInsertarUsuario)) {
        echo json_encode([
            'respuesta' => 'ok',
            'razon' => 'usuarioInsertado'
        ]);
    }

} catch (Exception $e) {

    // Visualizando el error si existe
    echo 'Error al procesar';
}

The problem is when I try to process the JSON object that is sent using an echo in the PHP code, I would like to get that JSON object for always having a feedback according to what happened while the code execution. When I try to read this object in Kotlin, I always get this error:

com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

So I tought this could be a problem using echo in PHP, so I tried to use this file using POSTMAN, and it works, I get an answer either the field correo has an already taken value or not.

When using a correo value already taken:

{"respuesta":"error","razon":"EmailEnUso"}

When using a different one never used:

{"respuesta":"ok","razon":"usuarioInsertado"}

This is the Kotlin code:

// Cola de peticiones
        val queue = Volley.newRequestQueue(this)

        // Tomamos los datos
        val nombre = etextNombreRegistro.text.toString()
        val apellido = etextApellidoRegistro.text.toString()
        val correo = etextCorreoRegistro.text.toString()
        val contrasenia = etextContraseniaRegistro.text.toString()

        // Guardando parámetros en hash para mandarlos como JSON en post
        val params = HashMap<String, String>()
        params["nombre"] = nombre
        params["apellido"] = apellido
        params["correo"] = correo
        params["contrasenia"] = contrasenia
        val jsonObject = JSONObject(params as Map<String, String>)

        // Petición con volley
        val request = JsonObjectRequest(Request.Method.POST, Urls.ServicioRegistro, jsonObject,
                { response ->
                    Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show()
                }, { error ->
                    Toast.makeText(this, "Error: " + error.toString(), Toast.LENGTH_LONG).show()
                    Log.d("MENSAJE", error.toString())
            }
        )

        // Procesandola
        queue.add(request)

For getting a JSON object as an answer in Kotlin must I use another method or making another parse ?. As I said, actually the PHP code is working and is inserting new records, but how can I receive a JSON object as answer from PHP to Kotlin without getting this error?

André Walker
  • 588
  • 10
  • 30

0 Answers0