如何在 android 的 textview 中显示与 JsonObject 的距离和位置?
How to display distance and location from JsonObject in textview in android?
我在显示从 JsonObject
return 从 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);
}
用名称 Constant
生成一个 Java Class 并像这样初始化你的两个变量距离和持续时间
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);
我在显示从 JsonObject
return 从 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);
}
用名称 Constant
生成一个 Java Class 并像这样初始化你的两个变量距离和持续时间
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);