get a String from a VolleySingleton request on Android

0

I have a database on an external server, I want to check that the value that the user has entered for a field does not exist in a column of my table previously, if it is so warn and prevent it from advancing in the application. I use this php code to connect to the server:

<?php
/**
 * Obtiene el detalle de una meta especificada por
 * su identificador 
 */

require 'pistes.php';

if ($_SERVER['REQUEST_METHOD'] == 'GET') {

    if (isset($_GET['nom_usuari'])) {

        // Obtener parámetro idMeta
        $parametro = $_GET['nom_usuari'];

        // Tratar retorno
        $retorno = pistes::getByNom_usuari($parametro);


        if ($retorno) {

            $pistes["estado"] = "1";
            $pistes["pistes"] = $retorno;
            // Enviar objeto json de la meta
            print json_encode($pistes);
        } else {
            // Enviar respuesta de error general
            print json_encode(
                array(
                    'estado' => '2',
                    'mensaje' => 'No se obtuvo el registro'
                )
            );
        }

    } else {
        // Enviar respuesta de error
        print json_encode(
            array(
                'estado' => '3',
                'mensaje' => 'Se necesita un identificador'
            )
        );
    }
}

Use Singleton volleyball to make the request:

 bt_acabar.setOnClickListener(new View.OnClickListener() {
            //validació de que el nom de la partida i el nom de l'usuari no existeixin a la taula
            @Override
            public void onClick(View v) {



                VolleySingleton.
                        getInstance(getApplicationContext()).
                        addToRequestQueue(
                                new JsonObjectRequest(
                                        Request.Method.GET,
                                        "http://gimcana.esy.es/obtenir_pistes_nom_partida.php?nom_partida="
                                                +nom_partida.getText().toString(),
                                        jsonObject,
                                        new Response.Listener<JSONObject>() {

                                            @Override
                                            public void onResponse(JSONObject response) {
                                                // Procesar la respuesta Json
                                                String estado = null;

                                                try {
                                                    estado = response.getString("estado");
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }

                                                switch (estado) {
                                                    case "1":
                                                       resposta="invalid";


                                                        Toast.makeText(getApplicationContext(), "el nom de la partida ja ha estat utilitzat, creen un altre",
                                                                Toast.LENGTH_SHORT).show();
                                                        break;
                                                    case "2":

                                                        resposta="correcte";

                                                        Toast.makeText(getApplicationContext(), "nom de la partida correcte", Toast.LENGTH_SHORT).show();
                                                        break;
                                            }
                                        }},
                                        new Response.ErrorListener() {
                                            @Override
                                            public void onErrorResponse(VolleyError error) {

                                                resposta= "invalid";

                                                Log.d( TAG,"Error Volley: " + error.getMessage());
                                                Toast.makeText(getApplicationContext(), "error en la comprobació del nom de la partida", Toast.LENGTH_SHORT).show();
                                            }
                                        }

                                )


                        );

The toasts that I get indicate that I'm doing the process correctly, but when I go back to the main thread, the variable resposta is null , so checking It does not help me at all ...

I try to do it like this:

if(reposta=="correcte"){
  Intent intent = new Intent(setAct.this, segAct.class);
                Bundle b=new Bundle();
                intent.putExtra("nom_part",nom_partida.getText().toString());
                intent.putExtra("nom_usuari",nom_usuari.getText().toString());
                intent.putExtra("num_equips",num_equips.getText().toString());
                intent.putExtra("contras_usu",contras_usu.getText().toString());
                intent.putExtras(b);
                startActivity(intent);
}

The debugger tells me that the value of resposta is null , I imagine this happens because they are two different threads, can someone help me?

Thanks !!

    
asked by Martí Amat Vila 29.06.2017 в 12:25
source

1 answer

1

The call you are making is asynchronous so you may be running your block of code that creates the bundle before you get the answer.

Instead of using Toast, put a break point in the onResponse block of Volley and another at the beginning of the block where you create the Bundle, so you'll see that it runs before, if the onResponse or the Bundle block.

My advice is that you create a callback to pick up Volley's answer and know when the request to the service has ended.

Greetings.

    
answered by 29.06.2017 в 14:58