如何在android的textview中显示与JsonObject的距离和位置?

如何在android的textview中显示与JsonObject的距离和位置?,android,textview,google-directions-api,Android,Textview,Google Directions Api,我在显示从JsonObject从谷歌返回的距离和位置时遇到问题。我能够获取两点之间的位置和路线,但无法在TextView中显示距离和位置。 我只能使用 Log.d("distance", "Calculated distance:" + dist + " km "); 但无法通过textview/Toast显示它。我知道有类似的问题,但仍然无法解决我的问题 DirectionJsonParser.java public List<List<HashMap<String,

我在显示从
JsonObject
从谷歌返回的距离和位置时遇到问题。我能够获取两点之间的位置和路线,但无法在
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 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);
    }
公共列表解析(JSONObject jObject){
列表路由=新建ArrayList();
JSONArray jRoutes=null;
JSONArray jLegs=null;
JSONArray jSteps=null;
JSONObject jDistance=null;
JSONObject jDuration=null;
长距离=0;
整数秒=0;
试一试{
jRoutes=jObject.getJSONArray(“路由”);
/**穿越所有路线*/
对于(int i=0;i
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

 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 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);
    }
TextView距离、持续时间;
距离=(TextView)findViewById(R.id.display\u距离);
持续时间=(TextView)findViewById(R.id.display\u持续时间);
专用无效提取路线(最终位置、最终请求){
//清除所有多段线
如果(多段线!=null)
polyline.remove();
if(request.getAddress()!=null&&!request.getAddress().isEmpty()){
mService.getGeoCode(request.getAddress()).enqueue(新回调()函数){
@凌驾
公共void onResponse(调用、响应){
试一试{
JSONObject=newJSONObject(response.body().toString());
字符串lat=((JSONArray)jsonObject.get(“结果”))
.getJSONObject(0)
.getJSONObject(“几何体”)
.getJSONObject(“位置”)
.get(“lat”).toString();
字符串lng=((JSONArray)jsonObject.get(“结果”))
.getJSONObject(0)
.getJSONObject(“几何体”)
.getJSONObject(“位置”)
.get(“lng”).toString();
最终LatLng订单位置=新LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
位图Bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.deliverybox);
位图=Common.scaleBitmap(位图,70,70);
MarkerOptions marker=newmarkeroptions().icon(BitmapDescriptorFactory.fromBitmap(位图))
.title(“顺序”+Common.currentRequest.getPhone())
.位置(订单位置);
mMap.addMarker(marker);
//绘制路线
mService.getDirections(yourLocation.latitude+,“+yourLocation.longitude,
orderLocation.latitude+,“+orderLocation.longitude)
.enqueue(新的回调函数(){
@凌驾
公共void onResponse(调用、响应){
新建ParserTask().execute(response.body().toString());
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});
}捕获(JSONException e){
e、 printStackTrace();
}
}
私有类ParserTask扩展了AsyncTask{
ProgressDialog mDialog=新建ProgressDialog(TrackingOrder.this);
@凌驾
distance.setText(Constant.DISTANCE);
duration.setText(Constant.DURATION);