consume a PHP service on Android

0

I am trying to consume a Service from Android, and it does not mark me error but it does not show me the records

My PHP Code I changed my PHP Code and I still can not get the records.

    <?php
    $consulta=$_GET["Code"]
    try{ 
    $usuario = "xxxxxxx"; 
    $password = "xxxxx"; 
    $conn = new PDO('mysql:host=xxxxxx;dbname=xxxxx', $usuario, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $conn->exec("SET CHARACTER SET utf8");

   $sql="SELECT Code,user,Pass,TipoUsuario FROM Usuarios WHERE Code= :Code";
    $resultado=$conn->prepare($sql);
    $resultado ->execute(array($consulta));
    $registro=$resultado->fetchAll(PDO::FETCH_ASSOC);
    $json=json_encode($registro);

    return $json;

   }catch(PDOException $e){ 
     echo 'No existe  un usuario  con este código'; 
   }
?>

This is my Config class.

//URL  DE  MI CÓDIGO  PHP
    public static final String URL_ADD_USER="http://ejemplo.atwebpages.com/conect/addUser.php";
    public static final String URL_GET_USER = "http://ejemplo.atwebpages.com/conect/busquedaUser.php?Code=";


  // obtengo valores
   public static final String KEY_USER_CODE = "Code";
   public static final String KEY_USER_USUARIO = "user";
   public static final String KEY_USER_PASS = "Pass";
   public static final String KEY_USER_TIPOUSER = "TipoUsuario";

   // El result
    public static final String TAG_JSON_ARRAY="result";

This is my Java code.

 private void getData() {
    String Code= et1.getText().toString().trim();
    if (Code.equals("")) {
        Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
        return;
    }
    loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

    String url = Config.URL_GET_USER+et1.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            showJSON(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(buscarUpdateUser.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
private void showJSON(String response){
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
        JSONObject collegeData = result.getJSONObject(0);
        String  User = collegeData.getString(Config.KEY_USER_USUARIO);
        String Pass = collegeData.getString(Config.KEY_USER_PASS);
        String TipoUsuario = collegeData.getString(Config.KEY_USER_TIPOUSER);

        et2.setText(User);
        et3.setText(Pass);
        SeleccionaItemTipoUsuario(tipUser,TipoUsuario);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
    
asked by Sofia 07.03.2017 в 00:34
source

2 answers

0

I have often had the same problem and I find that accents and strange characters are always the problem.

Check the output of json_encode() , if it is false the problem is in the data that you consult.

Always try to pass the output (data) to UTF-8 before passing it to json_encode() .

    
answered by 12.06.2017 в 18:36
0

Your code expects a result of type string, but formatted in JSON style:

    public void onResponse(String response) {

Said result, called response is sent in parameter to the method:

        showJSON(response);

which makes it a JSON object:

    JSONObject jsonObject = new JSONObject(response);

The problem:

From your PHP, which queries by sending the URL, you are not returning what Android expects, that is, a string in the form of JSON.

Something like this:

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

If you go to this URL you will see an example of a functioning web service: link If your web service (PHP) works well, should return something similar.

Solution:

Your PHP code needs a touch up. This part of the code:

$sql="SELECT Code,user,Pass,TipoUsuario FROM Usuarios";
$resultado=$conn->prepare($sql);
$resultado ->execute();
while($registro=$resultado->fetch(PDO::FETCH_ASSOC))
{
    echo Code.$registro[0];
    echo user. $registro[1];
    echo Pass.$registro[2];
    echo TipoUsuario.$registro[3];

It's simpler. It would be something like this:

$sql="SELECT Code,user,Pass,TipoUsuario FROM Usuarios";
$resultado=$conn->prepare($sql);
$resultado ->execute();
/*
 * Esto sobra
 * while($registro=$resultado->fetch(PDO::FETCH_ASSOC))
 * {
 *   echo Code.$registro[0];
 *   echo user. $registro[1];
 *   echo Pass.$registro[2];
 *   echo TipoUsuario.$registro[3];


/*
 * Si Android espera un JSON, lo construyes aquí
 * Simplemente convirtiendo los datos recibidos
 * a JSON, usando json_encode
 *
 */
$registro=$resultado->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($registro);

/* Estas dos líneas son muyyyy importantes. Tu código devuelve el JSON a Android */
header('Content-Type: application/json');
return $json;

It should work, unless there is another error in the code or the server is not returning anything from PHP. You can prove that by doing System.out.println of the result you receive.

Still not showing anything after these changes?

Try sending the URL to your web service from the browser just as you send it from android. If you return a JSON similar to the example above, the code of showJSON(response); has to be revised, you may not be parsing well the JSON received. If when you put the URL in the browser you do not see the results of type JSON, it is very possible that for some reason the SQL query is not returning anything.

    
answered by 07.03.2017 в 01:58