How to read a JSON that is sent from a webservice on Android?

0

Hi, I have a php file in a hosting, this file consults and returns the data through a JSONArray.

$idusu=$_GET['pkusu'];
$pass=$_GET['passw'];
if($_GET['opc']=="1")
{
   $sql="consulta...";
    $r2=mysql_query($sql) or die(mysql_error());
    if(mysql_num_rows($r2));
    {
      while ($arr=mysql_fetch_array($r2))
      {
        echo json_encode($arr);
      }  
    } 
}

In android I create a JASONArray and I pass the data to you by getstring this to pass the data to another activity and check the type of user

JSONArray ja = null;
try
{
 ja = new JSONArray(result);
 pk=ja.getString(0);
 nomb=ja.getString(1);
 tipo=ja.getString(2);
 if (tipo == "x")
 {
   Intent i = new Intent(MainActivity.this, Main2Activity.class);
   i.putExtra("nomb", nomb);
   startActivity(i);
   finish();
 }
 else
 if(tipo=="y")
 {
   Intent i = new Intent(MainActivity.this, ProductosAdmin.class);
   i.putExtra("nomb", nomb);
   startActivity(i); 
   finish();           
 }
}
catch (JSONException e)
{
  e.printStackTrace();
}

I do not understand what is wrong with the code if you execute the direct php in the url of the page if it shows the JSON but does not show it in android.

    
asked by Leonardo 09.12.2017 в 03:03
source

1 answer

1

To read your JSON on android an alternative is by means of a Asynctask , there are other libraries like retrofit , volley .

In this case I will show you how to do it with an Asynctask ( see documentation )   and then show your data in a listview to verify that it reads them, then you can perform the action you want. removing listview , etc

// declaramos dos variables para manejar el tiempo de conexión y un String para almacenar-mostrar los datos depues en el listview
String pregrespcomment; 
ListView mostrarr;
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;

 private class leer_datos extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(ganancias_totales.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdLoading.setMessage("\tConsultando...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        @Override
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://www.tu_sitio/tu_archivo.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try 
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();  
                if (response_code == HttpURLConnection.HTTP_OK) {  
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }

        @Override
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
                final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(ganancias_totales.this);
                alertaDeError.setTitle("Error");
                alertaDeError.setMessage("Ups, no se han podido cargar los datos. Intentelo de nuevo.");
                alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                alertaDeError.create();
                alertaDeError.show();
            } else {
                //Existen Datos
                List<String> preguntas = new ArrayList<String>();
                JSONArray jsonArray = null;
                try {
                    jsonArray = new JSONArray(result);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject preguntaDatos = null;
                        try {
                            preguntaDatos = jsonArray.getJSONObject(i);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        try {
                            assert preguntaDatos != null;
                            pregrespcomment =" datos: " + "\n" +">+ preguntaDatos.getString("pkusu"),preguntaDatos.getString("pass");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        preguntas.add(pregrespcomment);

                    }

                    //crear el Adapter.
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ejemplo.this, android.R.layout.simple_list_item_1, preguntas);
                    mostrarr.setAdapter(adapter);


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

                    final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(ganancias_totales.this);
                    alertaDeError.setTitle("Error");
                    alertaDeError.setMessage("Ups, no existen datos. Intentelo de nuevo.");
                    alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    alertaDeError.create();
                    alertaDeError.show();
                }
            }
        }


    }
    
answered by 09.12.2017 в 07:34