Ricardo Villanueva
Ricardo Villanueva

Reputation: 23

Problem passing parameters from android to php

I have a problem with my android application when sending parameters with volley, I have to show the data of a user who logged into my app, the data is in a server, in my php I return it with Json, it works very well when the I send with parameters in the php, but in the volley getParams doesn't send the values ​​of my global variables.

attach code:

MainLista.java here I read the Json

public class MainLista extends AppCompatActivity {

    TextView txt1;
    ListView listaPerfil;
    ArrayAdapter adapter;
    HttpURLConnection con;

    String LINK = "phpurl";
    String url = LINK + "?email=" + Globales.USER_EMAIL + "?pass=" + Globales.USER_PASS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_lista);
        listaPerfil = findViewById(R.id.listaPerfil);

        txt1 = findViewById(R.id.txt1);

        txt1.setText("email: " + Globales.USER_EMAIL + "\nPASS: " + Globales.USER_PASS);

        StringRequest sr = new StringRequest(Request.Method.POST, url, response -> { }, error -> {

            Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();

        }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new Hashtable<>();
                params.put("email", Globales.USER_EMAIL);
                params.put("contrasena", Globales.USER_PASS);

                Log.d("IMPRESION", Globales.USER_EMAIL);
                Log.d("IMPRESION", Globales.USER_PASS);

                return params;
            }
        };

        RequestQueue rq = Volley.newRequestQueue(this);
        rq.add(sr);

        try {
            ConnectivityManager connMgr =(ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {

                new JsonTask().execute(new URL("phpurl"));

            } else {

                Toast.makeText(this, "ERROR DE CONEXION", Toast.LENGTH_LONG).show();

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private class JsonTask extends AsyncTask<URL, Void, List<Datos>> {

        @Override
        protected List<Datos> doInBackground(URL... urls) {
            List<Datos> datos = null;

            try {
                con = (HttpURLConnection)urls[0].openConnection();
                con.setConnectTimeout(15000);
                con.setReadTimeout(10000);

                int statusCode = con.getResponseCode();

                if (statusCode != 200) {
                    datos = new ArrayList<>();
                    datos.add(new Datos("error", null, null, null, null, null, null));
                } else {
                    InputStream in = new BufferedInputStream(con.getInputStream());

                    JsonParser parser = new JsonParser();

                    datos = parser.leerFlujoJson(in);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                con.disconnect();
            }
            return datos;
        }

        @Override
        protected void onPostExecute(List<Datos> datos) {
            if (datos != null) {
                adapter = new AdaptadorDatos(MainLista.this, datos);
                listaPerfil.setAdapter(adapter);

            } else {
                Toast.makeText(getBaseContext(), "ERROR DE PARSING JSON", Toast.LENGTH_LONG).show();
            }
        }
    }
}

php:

<?
    session_start();
    include('Conexion2.php');

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

    $email  = $_GET['email'];
    $pass   = $_GET['contrasena'];

    $sql="SELECT c.nombre, c.apellido, c.telefono1, c.email, c.fechanacimiento, c.contrasena, f.imagen
            FROM clientes AS c
            INNER JOIN fotos AS f ON c.clienteid = f.clienteid
            WHERE c.email = '$email' AND c.contrasena = '$pass'";

$pdo = pdo();
$query = $pdo -> prepare($sql);
$query -> execute(array($cons));
$res = $query -> fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($res);

echo $json;
    }
?>

obtainen Json from php:

[{"nombre":"Fernando","apellido":"Villarreal","telefono1":"8672554040","email":"[email protected]","fechanacimiento":"2021-02-11","contrasena":"12345678","imagen":"https:**********/FP-aYRsz-891.png"}]

Upvotes: 2

Views: 114

Answers (1)

Shay Kin
Shay Kin

Reputation: 2677

In your PHP code you use the GET method and in Volley you use POST so for this to work you have 2 chose change your php to:

<?
    session_start();
    include('Conexion2.php');



    $email  = $_POST['email'];
    $pass   = $_POST['contrasena'];

    $sql="SELECT c.nombre, c.apellido, c.telefono1, c.email, c.fechanacimiento, c.contrasena, f.imagen
            FROM clientes AS c
            INNER JOIN fotos AS f ON c.clienteid = f.clienteid
            WHERE c.email = '$email' AND c.contrasena = '$pass'";

$pdo = pdo();
$query = $pdo -> prepare($sql);
$query -> execute(array($cons));
$res = $query -> fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($res);

echo $json;
    
?>

Or change The Volley code to this :

 StringRequest sr = new StringRequest(Request.Method.GET, url, response -> { }, error -> {

        Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();

    
    });
    
}

and also you need to change your change your Link to this :

 String LINK = "https://viavel.com.mx/pruebas/PHPRicardo/ejemplomostrar.php"; 
 String url = LINK + "?email=" + Globales.USER_EMAIL + "&pass=" +Globales.USER_PASS;

for multiple values in GET Method you must add '&' between the values

Upvotes: 1

Related Questions