Problem with Asyntask-PHP

1

My PHP

<?php
require "dbconfig.php";

$con=mysqli_connect($servername,$username,$password,$dbname) or die('Unable to connect');
if(mysqli_connect_error($con))
{
  echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name=$_POST['Query'];
$sql="SELECT name_user,SUM(cash_car) FROM usuario u 
INNER JOIN 
carro c ON u.id_user=c.id_user 
WHERE u.name_user='elias';";
$query=mysqli_query($con,$sql);
if($query)
{
    while($row=mysqli_fetch_array($query))
  {
    $data[]=$row;
  }
    print(json_encode($data));
}else
{
  echo('Not Found ');
}
mysqli_close($con);

I get the following from the file PHP

[{"0":"elias","name_user":"elias","1":"10","SUM(cash_car)":"10"}]

And I just wanted to show the total of the SUM function which is 10 in this case, since the other field (user_name) is only to filter the result.

But executing the query using asyntask the app stops working.

 private class AsyncRetrieve 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://bdauditorio.esy.es/total_carros/ver_total_elias.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 las cuentas. 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 =" Cuenta" + "\n" +"> Total ganacias: "+ preguntaDatos.getString("cash_car");

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

                    }

                    //crear el Adapter.
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ganancias_totales.this, android.R.layout.simple_list_item_1, preguntas);
                    mostrarr.setAdapter(adapter);
                   // mostrarr.getAdapter().getCount();
                    //Toast.makeText(getApplicationContext(), "Total de cuentas: " + mostrarr.getAdapter().getCount() , Toast.LENGTH_LONG).show();

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

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


    }
    
asked by Ashley G. 31.10.2017 в 22:27
source

1 answer

1

Take a good look at your JSON. It does not have any key called cash_car therefore this line of code will fail: ... preguntaDatos.getString("cash_car");

That is solved by giving the% cash_car to the column doing the sum in the SELECT.

That is: SELECT ... SUM(...) cash_car... now you will have a key named like this in your JSON.

Note that using AS cash_car is optional.

I did not check all your code, but you should know that any JSON key that you want to obtain without it exists will crash your app.

Another thing to keep in mind when you get values from a key of a JSON object is the data type. If the value is an integer you must use getInt e time of getString .

    
answered by 31.10.2017 / 23:32
source