2

Tengo este bloque de código quiero saber por que en el if (polylinesOptions != null).... al ejecutar mi programa se salta ese if y se va directo a else. Quisiera saber cómo puedo hacer que no retorne null porque según tengo entendido no entra al if por que no está encontrando ningun valor, entonces se va directo al else, pero quisiera saber si me podrian ayduar a que entre al if, por favor y gracias.

@Override
    protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
       // ---------recibe la lista de rutas en el mapa----------
        ArrayList points ;
        PolylineOptions polylineOptions = null;

        for (List<HashMap<String, String>> path : lists){
            points = new ArrayList();
            polylineOptions = new PolylineOptions();

            for (HashMap<String, String> point : path){
                double lat = Double.parseDouble(point.get("lat"));
                double lon = Double.parseDouble(point.get("lon"));

                points.add(new LatLng(lat,lon));

            }
            polylineOptions.addAll(points);
            polylineOptions.width(15);
            polylineOptions.color(Color.BLUE);
            polylineOptions.geodesic(true);
        }


        if (polylineOptions != null){
            map.addPolyline(polylineOptions);


        }else{
            Toast.makeText(requireActivity(),"Direccion no encontrada", Toast.LENGTH_SHORT).show();
        }

    }
}

Y este es el DirectionsParser, aquí esta el JSON y lists como pueden ver, esta clase es solo para que el JSON almacene las rutas y contiene polylines y los puntos viene latitud y longitud de donde las obtengo, etc. Cualquier duda o aclaración estoy al pendiente gracias


package com.example.igo;

import com.google.android.gms.maps.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;



public class DirectionsParser {


    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            // Loop for all routes
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<HashMap<String, String>>();

                //Loop for all legs
                for (int j = 0; j < jLegs.length(); j++) {
                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    //Loop for all steps
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List list = decodePolyline(polyline);

                        //Loop for all points
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
                            hm.put("lon", Double.toString(((LatLng) list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

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

        return routes;
    }

    private List decodePolyline(String encoded) {

        List poly = new ArrayList();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

Esta es la parte donde dicen AsyncTask lo uso en estas dos clases


        @Override
        protected String doInBackground(String... strings) {
           String responseString = "";
            try {
                responseString = requestDirections(strings[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
  //---------------EL PARSEO DEL JSON ESTA AQUI DEBAJO---------
            TaskParser taskParser = new TaskParser();
            taskParser.execute(s);

        }
    }
    public class TaskParser extends AsyncTask<String, Void, List<List<HashMap<String, String>>> >{

        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
            JSONObject jsonObject = null;
            List<List<HashMap<String, String>>> routes = null;
            try {
                jsonObject = new JSONObject(strings[0]);
                DirectionsParser directionsParser = new DirectionsParser();
                routes = directionsParser.parse(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return routes;
        }

Esta es mi clase DirectionParser que estoy usando para que lo vean también

package com.example.igo;

import com.google.android.gms.maps.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class DirectionsParser {


    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            // Loop for all routes
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<HashMap<String, String>>();

                //Loop for all legs
                for (int j = 0; j < jLegs.length(); j++) {
                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    //Loop for all steps
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List list = decodePolyline(polyline);

                        //Loop for all points
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
                            hm.put("lon", Double.toString(((LatLng) list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

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

        return routes;
    }

    private List decodePolyline(String encoded) {

        List poly = new ArrayList();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}
```
8
  • Y vos podes asegurar que llega algo en lists a esta funcion? pq si no llega nada, se va por el else. Y otra cosa, solo vas a agregar al map la ultima PolyLineOptions, porque en el for haces un nuevo objeto en cada vuelta pero no lo guardas?
    – gbianchi
    el 5 jul. 2019 a las 15:52
  • no no se guarda es para si hacen otra busqueda borre la anterior ,y no no puedo asegurar que llega algo a lists pero en mi otra clase que se llama DirectionsParser ahi esta lists y de ahi pido los datos que en teoria se deberían almacenar te lo adjunto arriba en la publicacion ,gracias por contestar el 5 jul. 2019 a las 16:19
  • Primero verifica que llegue algo. Despues ese for no sirve solo estas guardando el ultimo valor de la lista que recorres.
    – gbianchi
    el 5 jul. 2019 a las 16:31
  • @alexisGonzalezGarcia como comenta gbianchi, doInBackground() debe retornar valores en la lista, verifica que esto suceda
    – Jorgesys
    el 5 jul. 2019 a las 16:44
  • @alexisGonzalezGarcia veo tu actualización, te comento que no es necesario llamar en onPostExecute() otro Asyntask, todo lo puedes realizar en doInBackground() de un solo Asynctask, Primeramente dime ¿que valor de "s" se obtiene en protected void onPostExecute(String s) {?
    – Jorgesys
    el 5 jul. 2019 a las 17:32

1 respuesta 1

0

La razón es que tu Asynctask no esta obteniendo la lista que es enviada a onPostExecute() , cuando esta lista no tiene elementos, la variable polylineOptions se mantiene con valor null:

@Override
    protected void onPostExecute(List<List<HashMap<String, String>>> lists) {

   // ---------recibe la lista de rutas en el mapa----------
        ArrayList points ;
        PolylineOptions polylineOptions = null;

        for (List<HashMap<String, String>> path : lists){
      ...
     ...

    }
}

en este caso debes asegurar que doInBackground() de tu Asynctask retorne valores en la lista

  @Override
       protected Integer doInBackground() {
          ...
          ...
         ...
         return lists;
    }

de otra forma siempre polylineOptions tendrá un valor null.

3
  • me podrias ayudar con un ejemplo por favor como deveria corregir esto por favor es que no me quedo un poco claro por favor @Elenasys el 5 jul. 2019 a las 17:11
  • @alexisGonzalezGarcia el problema es el proceso que se realiza en doInBackground() , agrega tu Asynctask en la pregunta por favor.-
    – Jorgesys
    el 5 jul. 2019 a las 17:12
  • aqui uso el AsyncTask @Elenasys el 5 jul. 2019 a las 17:23

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.