Как отобразить расстояние и местоположение от JsonObject в текстовом представлении в Android? - PullRequest
1 голос
/ 04 апреля 2019

У меня проблема с отображением расстояния и местоположения от JsonObject возврата от Google.Я могу получить местоположение и маршрут между двумя точками, но я не могу отобразить расстояние и местоположение в TextView.Я могу отобразить его только с помощью

Log.d("distance", "Calculated distance:" + dist + " km "); 

, но не могу отобразить его с помощью textview / Toast.Я знаю, что есть похожие вопросы, но все еще не могу решить мою проблему.

DirectionJsonParser.java

 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;
    JSONObject jDistance = null;
    JSONObject jDuration = null;
    long totalDistance = 0;
    int totalSeconds = 0;

    try {

        jRoutes = jObject.getJSONArray("routes");

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


            /** Traversing all legs */
            for (int j = 0; j < jLegs.length(); j++) {

                jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                totalDistance = totalDistance + Long.parseLong(jDistance.getString("value"));


                /** Getting duration from the json data */
                jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                totalSeconds = totalSeconds + Integer.parseInt(jDuration.getString("value"));


                /** Traversing 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 = decodePoly(polyline);

                    /** Traversing 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("lng", Double.toString(((LatLng) list.get(l)).longitude));
                        path.add(hm);
                    }
                }
                routes.add(path);

                double dist = totalDistance / 1000.0;
                Log.d("distance", "Calculated distance:" + dist + " km ");


                int days = totalSeconds / 86400;
                int hours = (totalSeconds - days * 86400) / 3600;
                int minutes = (totalSeconds - days * 86400 - hours * 3600) / 60;
                int seconds = totalSeconds - days * 86400 - hours * 3600 - minutes * 60;
                Log.d("duration", days + " days " + hours + " hours " + minutes + " mins " + seconds + " seconds ");

            }
        }

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

    return routes;
}

TextView

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="DISTANCE"
    android:textSize="20sp"
    android:textStyle="bold"
    android:textColor="@android:color/holo_red_dark"
    android:id="@+id/display_distance"/>

<TextView
    android:id="@+id/display_duration"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:text="DURATION"
    android:textColor="@android:color/holo_red_dark"
    android:textSize="20sp"
    android:textStyle="bold" />

TrackingOrder.java

 TextView distance,duration;

  distance = (TextView)findViewById(R.id.display_distance);
  duration = (TextView)findViewById(R.id.display_duration);
 private void drawRoute(final LatLng yourLocation, final Request request) {

    //clear all polyline
    if (polyline != null)
        polyline.remove();

    if (request.getAddress() != null && !request.getAddress().isEmpty()) {
        mService.getGeoCode(request.getAddress()).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());

                    String lat = ((JSONArray) jsonObject.get("results"))
                            .getJSONObject(0)
                            .getJSONObject("geometry")
                            .getJSONObject("location")
                            .get("lat").toString();

                     String lng = ((JSONArray) jsonObject.get("results"))
                            .getJSONObject(0)
                            .getJSONObject("geometry")
                            .getJSONObject("location")
                            .get("lng").toString();

                    final LatLng orderLocation = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));

                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.deliverybox);
                    bitmap = Common.scaleBitmap(bitmap, 70, 70);

                    MarkerOptions marker = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                            .title("Order of " + Common.currentRequest.getPhone())
                            .position(orderLocation);

                    mMap.addMarker(marker);

                    //draw route

                    mService.getDirections(yourLocation.latitude + "," + yourLocation.longitude,
                            orderLocation.latitude + "," + orderLocation.longitude)
                            .enqueue(new Callback<String>() {
                                @Override
                                public void onResponse(Call<String> call, Response<String> response) {

                                    new ParserTask().execute(response.body().toString());

                                }

                                @Override
                                public void onFailure(Call<String> call, Throwable t) {

                                }
                            });

                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }

 private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    ProgressDialog mDialog = new ProgressDialog(TrackingOrder.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mDialog.setMessage("Please waiting...");
        mDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... strings) {

        JSONObject jsonObject;

        List<List<HashMap<String, String>>> routes = null;


        try {
            jsonObject = new JSONObject(strings[0]);

            DirectionJSONParser parser = new DirectionJSONParser();

            routes = parser.parse(jsonObject);


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

        return routes;

    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
        mDialog.dismiss();

        ArrayList points = null;
        PolylineOptions lineOptions = null;

        for (int i = 0; i < lists.size(); i++) {

            points = new ArrayList();
            lineOptions = new PolylineOptions();

            List<HashMap<String, String>> path = lists.get(i);

            for (int j = 0; j < path.size(); j++) {

                HashMap<String, String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));

                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            lineOptions.geodesic(true);
        }

        mMap.addPolyline(lineOptions);
    }

1 Ответ

0 голосов
/ 04 апреля 2019

Создайте один Java-класс с именем Constant и инициализируйте две переменные расстояния и длительности следующим образом:

public class Constant {
    public static String DISTANCE= "";
    public static String DURATION= "";
}

Теперь в вашем DirectionJsonParser.java

            double dist = totalDistance / 1000.0;
           Constant.DISTANCE = String.valueof(dist); //CHECK HERE
            Log.d("distance", "Calculated distance:" + dist + " km ");


            int days = totalSeconds / 86400;
            int hours = (totalSeconds - days * 86400) / 3600;
            int minutes = (totalSeconds - days * 86400 - hours * 3600) / 60;
            int seconds = totalSeconds - days * 86400 - hours * 3600 - minutes * 60;

            Constant.DURATION= String.valueof(days + " days " + hours + " hours " + minutes + " mins " + seconds + " seconds "); //CHECK HERE

            Log.d("duration", days + " days " + hours + " hours " + minutes + " mins " + seconds + " seconds ");

И в вашем TrackingOrder

distance.setText(Constant.DISTANCE);
duration.setText(Constant.DURATION);
...