Execution order in AsyncTask inside loop - android

I have a problem concerning execution order.I get some data from server ( cities names , LatLng) and on onPostExecute i'm trying to calculate distances between cities. During last onPostExecute there are some distance calculations. The problem is that in
for(j=0;j<3;j++) {
or = markerPoints.get(j);
dest = markerPoints.get(j+1);
Log.d("or", or.toString());
Log.d("dest", dest.toString());
// Getting URL to the Google Directions API
String url = getDirectionsUrl(or, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
downloadTask is executed for the first time after loop "for" is completed, that means when j equals 2. Why not 3 times; Isn't that weird;
My whole code
public class Check_Itineraries1 extends FragmentActivity {
private ProgressDialog pDialog;
String username , origin_lat ,origin_lng ,destination_lat ,destination_lng ,
waypoint1_lat ,waypoint1_lng ,waypoint2_lat ,waypoint2_lng ,waypoints ,
origin_lat_pro ,origin_lng_pro ,destination_lat_pro ,destination_lng_pro , start_pro , final_pro;
int i, j ,b ;
double x,z ,t ,s;
TextView v1 , v2;
ArrayList<Double> Array = new ArrayList<Double>();
ArrayList<Double> Array_add = new ArrayList<Double>();
ArrayList<Double> Array_dif = new ArrayList<Double>();
ListView list;
ArrayList<LatLng> markerPoints;
// URL to get contacts JSON
private static String LOGIN_URL = "http://**************************";
public static final String PREFS_NAME = "MyPreferencesFile";
// JSON Node names
JSONParser jsonParser = new JSONParser();
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> itinList , final_itinList ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkitineraries);
itinList = new ArrayList<HashMap<String, String>>();
new GetData().execute();
}
private class GetData extends AsyncTask<Void, Void, Void> {
public void onPreExecute() {
super.onPreExecute();
Log.d("meg", "meg");
pDialog = new ProgressDialog(Check_Itineraries1.this);
pDialog.setMessage("Επεξεργάζομαι τα δεδομένα...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
username = settings.getString("username", "nikos");
}
protected Void doInBackground(Void... args) {
// TODO Auto-generated method stub
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// JSONObject jObj = new JSONObject();
JSONArray itin_results = json.getJSONArray("itin_results");
for (int i = 0; i < itin_results.length(); i++) {
JSONObject c = itin_results.getJSONObject(i);
String username = c.getString("username");
String startPoliPro = c.getString("startPoliPro");
String start_lat_pro = c.getString("start_lat_pro");
String start_lng_pro = c.getString("start_lng_pro");
String finalPoliPro = c.getString("finalPoliPro");
String final_lat_pro = c.getString("final_lat_pro");
String final_lng_pro = c.getString("final_lng_pro");
LinkedHashMap<String, String> pinakas = new LinkedHashMap<String, String>();
// adding each child node to HashMap key => value
pinakas.put("username", username);
pinakas.put("startPoliPro", startPoliPro);
pinakas.put("start_lat_pro", start_lat_pro);
pinakas.put("start_lng_pro", start_lng_pro);
pinakas.put("finalPoliPro", finalPoliPro);
pinakas.put("final_lat_pro", final_lat_pro);
pinakas.put("final_lng_pro", final_lng_pro);
// Διαλέγω αφετηρία και προορισμό του δρομολογίου του επαγγελματία
Log.d("1", username);
Log.d("2", startPoliPro);
Log.d("3", start_lat_pro);
Log.d("4", start_lng_pro);
Log.d("5", finalPoliPro);
Log.d("6", final_lat_pro);
Log.d("7", final_lng_pro);
itinList.add(pinakas);
b = itin_results.length(); // Είναι τα δρομολόγια των πελατων που ταιριάζουν ΣΥΝ το δρομολόγιο του επαγγελματία
Log.d("b", String.valueOf(b));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
origin_lat_pro = itinList.get(0).get("start_lat_pro").toString();
origin_lng_pro = itinList.get(0).get("start_lng_pro").toString();
destination_lat_pro = itinList.get(0).get("final_lat_pro").toString();
destination_lng_pro = itinList.get(0).get("final_lng_pro").toString();
start_pro = itinList.get(0).get("startPoliPro").toString();
final_pro = itinList.get(0).get("finalPoliPro").toString();
LatLng origin_pro = new LatLng(Double.parseDouble(origin_lat_pro),Double.parseDouble(origin_lng_pro));
LatLng destination_pro = new LatLng(Double.parseDouble(destination_lat_pro),Double.parseDouble(destination_lng_pro));
for (i = 0; i <b; i++) {
markerPoints = new ArrayList<LatLng>();
origin_lat = itinList.get(i).get("start_lat_pro").toString();
origin_lng = itinList.get(i).get("start_lng_pro").toString();
destination_lat = itinList.get(i).get("final_lat_pro").toString();
destination_lng = itinList.get(i).get("final_lng_pro").toString();
LatLng or = new LatLng(Double.parseDouble(origin_lat),Double.parseDouble(origin_lng));
LatLng dest = new LatLng(Double.parseDouble(destination_lat),Double.parseDouble(destination_lng));
markerPoints.add(origin_pro);
markerPoints.add(or);
markerPoints.add(dest);
markerPoints.add(destination_pro);
Log.d("a", markerPoints.get(0).toString());
Log.d("b", markerPoints.get(1).toString());
Log.d("c", markerPoints.get(2).toString());
Log.d("d", markerPoints.get(3).toString());
z = 0;
for(j=0;j<3;j++) {
or = markerPoints.get(j);
dest = markerPoints.get(j+1);
Log.d("or", or.toString());
Log.d("dest", dest.toString());
// Getting URL to the Google Directions API
String url = getDirectionsUrl(or, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}
}
//Αυτοτελές
private String getDirectionsUrl(LatLng or, LatLng dest) {
// Origin of route
String str_origin = "origin=" + or.latitude + ","+ or.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
Log.d("sos1", "sos1");
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
//Αυτοτελές//
//Αυτοτελές
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
Log.d("sos2", "sos2");
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
//Αυτοτελές//
// Fetches data from url passed
//Αυτοτελές
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("sos3", "sos3");
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
Log.d("sos4", "sos4");
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
//Αυτοτελές//
public class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
Log.d("sos5", "sos5");
// Starts parsing data
routes = parser.parse(jObject);
Log.d("json", jObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
String distance = "";
String duration = "";
Log.d("sos6", "sos6");
Log.d("result", String.valueOf(result.size()));
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
//
//
}
}
Log.d("finito", distance);
String asd[] = distance.split(" ");
Log.d("ass", asd[0]);
Log.d("ass", asd[1]);
double x = Double.parseDouble(asd[0]);
if(asd[1].equals("m")){
x = x/1000;
}
Log.d("intValue", String.valueOf(x));
x = Math.round(x);
Array.add(x);
Log.d("Array", Array.toString());
if(Array.size()==3){
z = Array.get(0) + Array.get(1) + Array.get(2);
Array_add.add(z);
Array.clear();
}
Log.d("size", String.valueOf(Array_add.size()));
Log.d("Αθροισμα", String.valueOf(z));
}
}
//Αυτοτελές
}

Android Developers says:
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with
{android.os.Build.VERSION_CODES#DONUT}, this was changed to a pool
of threads allowing multiple tasks to operate in parallel. Starting
with { android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed
on a single thread to avoid common application errors caused by
parallel execution.
Also since executor of AsyncTask is static so you get single executor of your application.
Now it already running GetData asyncTask and it runs asynsTask serially so it cannot execute your DownloadTask. It can run only after GetDataTask is finished.
If you want to run multiple asynctasks in parallel, you can look at Asynctask.executeOnExecutor().

Related

How to get distance by road through Google Map API

I want to get distance by road by foot and by car in my app.I have already got distance by line but now I want the exact distance. I have read to enable billing for google account for API key and I have done that. Now I couldn't understand he code I have seen multiple and tried them but can't understand how to use the API available at google guide. Sometimes the app crashes and sometime it gives nothing in response.
On priority what I want to do is to get the exact distance only it can be on foot or on vehicle any. Any help will be very grateful
The last code which I tried but its doing nothing
origin = new LatLng(currentLat, currentLong);
dest = new LatLng(donarLat, donarLong);
String url = getDirectionsUrl();
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
private String getDirectionsUrl() {
// Origin of route
String str_origin = "origin=" + currentLat + "," + currentLong;
// Destination of route
String str_dest = "destination=" + donarLat + "," + donarLong;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String key = "key=" + "**********NR9TxLUwXyeq0jwV6k************";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... urlList) {
try {
ArrayList<String> returnList = new ArrayList<String>();
for (String url : urlList) {
}
return returnList;
} catch (Exception e) {
Log.d("Background Task", e.toString());
return null; // Failed, return null
}
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(ArrayList<String> results) {
super.onPostExecute(results);
ParserTask parserTask = new ParserTask();
for (String url : results) {
parserTask.execute(url);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
try {
ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
// for (String url : jsonData) {
for (int i = 0; i < jsonData.length; i++) {
JSONObject jObject = new JSONObject(jsonData[i]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
}
return routes;
} catch (Exception e) {
Log.d("Background task", e.toString());
return null; // Failed, return null
}
}
#Override
protected void onPostExecute(ArrayList<List<HashMap<String, String>>> result) {
if (result.size() < 1) {
Toast.makeText(DonarList.this, "No Points", Toast.LENGTH_LONG).show();
return;
}
for (int i = 0; i < result.size(); i++) {
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
distance = point.get("distance");
continue;
}
}
Log.d("Distance: ", distance);
Toast.makeText(DonarList.this, "Your Distance ya hy :" + distance, Toast.LENGTH_SHORT).show();
}

how to add turn to turn navigation on map activity for multiple points

i have android map with multiple points plotted from mysql data..i have added basic features of map like mylocation,zoom etc...Also added direction between multiple points from mylocation.
Now I need to add step by step direction route or navigate between points.
Most importantly i dont want to redirect to google maps and naviagate..
all actions should happen withen my google map api.
here is my Mapactivity code onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Toast.makeText(getActivity(), Util.reslatitude + " " + Util.reslogitide+" "+Util.resname, Toast.LENGTH_LONG).show();
LatLng locations = new LatLng(Util.latitude,Util.longitude);
/* Location startPoint=new Location("locationA");
startPoint.setLatitude(Util.latitude);
startPoint.setLongitude(Util.longitude);
Location endPoint=new Location("locationA");
endPoint.setLatitude(13.073226);
endPoint.setLongitude(80.260921);
double distance=startPoint.distanceTo(endPoint);
Toast.makeText(this,String.valueOf(distance+" Meters"),Toast.LENGTH_SHORT).show();*/
/* LatLng loc = new LatLng(13.073226, 80.260921);*/
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
//mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setTrafficEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 4.2f));
mMap.addMarker(new MarkerOptions()
.title("User")
.position(locations)
);
/* // Getting URL to the Google Directions API
String url = getDirectionsUrl(locations, loc);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);*/
/*LatLng dest = new LatLng(13.036791,80.26763);
mMap.addPolyline(new PolylineOptions().add(locations,dest).color(Color.RED) //draws straight line between points
);*/
}
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < result.size(); i++) {
points = new ArrayList();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.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(12);
lineOptions.color(Color.BLUE);
lineOptions.geodesic(true);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
String mode = "mode=driving";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
help me to rectify the problem

Google Map V2 doesn't allow to draw route?

I want to draw route between my current location(Like Indore ) to Saudi Arabia.
I am able to draw route between indore to delhi ..but not from indore to saudi arabia.
I tried using intent by passing my lat long and saudi arabia's lat long, but google map app shows no route.
How can i do this?
You should make a call to the google directions api and draw a polyline on the map manually. You can use this methods:
public void setRoute() {
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Mode travel
//String mode = "mode=" + modeT; Uncomment this if you want choose a travel mode (driving, walking or transit)
// Departure Time, its neccesary to public transport
String departureTime = "";
if (modeT.equals("transit")) {
long seconds = (System.currentTimeMillis() / 1000);
departureTime = "&departure_time=" + seconds;
}
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode + departureTime;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
/**
* Fetches data from url passed
*/
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = ActFullMapOne.this.downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData)
{
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try
{
jObject = new JSONObject(jsonData[0]);
ApiDirectionsParser parser = new ApiDirectionsParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e)
{
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
//MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if (result.size() < 1) {
Toast.makeText(ActFullMapOne.this.getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for (int i = 0; i < result.size(); i++)
{
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
distance = point.get("distance");
continue;
} else if (j == 1) {
duration = point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(7);
lineOptions.color(Color.parseColor("#CC0060FF"));
}
// Drawing polyline in the Google Map for the i-th route
if (polyline != null)
polyline.remove();
polyline = ActFullMapOne.this.nMap.addPolyline(lineOptions);
}
}
EDIT 1. I just read your post better and I've seen that you only want to open the route on google maps. If you want to display the route on google maps app, use this method:
public void goToNavigation() {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + modLugar.latitud + "," + modLugar.longitud));
startActivity(Intent.createChooser(i, "Elige una aplicación"));
}

Show data from world weather online api

I am developing weather application by using world weather online API
for android.How i show data in application? data is showing in logcat.Following is my code.
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// adding contact to contact list
dataList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
}
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
First of all, this format will refer to the V1 free version. World Weather Online has released v2, which is superior. I was in the process of updating and saw this question sitting out there so I'll answer based off of what I had that did work.
You are on the right track to use the AsyncTask, here is my call to AsyncTask. You should know I use my "DataPoint" class to simply contain the data from WWO that I need to use. Based on your question, you can show the data that I will put in the DataPoint object in anyway you see fit on the screen, since at the end of the queryWeatherService(), you will end up with a parsed set of data.
//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{
// This method will retrieve the data from the weather service
DataPoint newDataPoint = new DataPoint();
if (!waiting)
{
try{
newDataPoint = new WeatherServiceClass().execute(
String.valueOf(getlatitude()), //Not shown here: pass in some String of a float value of of your lat coordinate.
String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
.get();
} catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
return newDataPoint;
// Documentation:
// https://developer.worldweatheronline.com/page/documentation
}
The WeatherServiceClass that extends the AsyncTask
public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
private String latitude;
private String longitude;
public WeatherServiceClass() {
}
#Override
protected DataPoint doInBackground(String... params) {
DataPoint dp = new DataPoint();
JSONWeatherParser jparser = new JSONWeatherParser();
latitude = params[0];
longitude = params[1];
String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
try {
dp = jparser.getWeather(data);
} catch (JSONException e) {
e.printStackTrace();
}
return dp;
//Reference:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
}
}
Here is the WeatherHttpClient class:
public class WeatherHttpClient {
private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";
public String getWeatherData(String latitude, String longitude){
HttpURLConnection con = null;
InputStream is=null;
try{
con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//Reading the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line=br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close();} catch(Throwable t){}
try { con.disconnect();} catch(Throwable t){}
}
return null;
}
Finally, here is my JSONWeatherParser:
public class JSONWeatherParser {
public JSONWeatherParser() {
}
public DataPoint getWeather(String data) throws JSONException {
DataPoint dp = new DataPoint();
Weather weather = new Weather(); //This is just a class that has a bunch of strings in it for the weather info.
JSONObject jObj = new JSONObject(data);
//Parsing JSON data
JSONObject dObj = jObj.getJSONObject("data");
JSONArray cArr = dObj.getJSONArray("current_condition");
JSONObject JSONCurrent = cArr.getJSONObject(0);
weather.setCurrent_temp(getString("temp_F",JSONCurrent));
weather.setHour(getString("observation_time",JSONCurrent));
JSONArray jArr = dObj.getJSONArray("weather");
JSONObject JSONWeather = jArr.getJSONObject(0);
JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
JSONObject JSONIcon = jArrIcon.getJSONObject(0);
weather.setDate(getString("date",JSONWeather));
weather.setPrecipmm(getString("precipMM",JSONWeather));
weather.setTempMaxc(getString("tempMaxC",JSONWeather));
weather.setTempMaxf(getString("tempMaxF",JSONWeather));
weather.setTempMinf(getString("tempMinF",JSONWeather));
weather.setTempMinc(getString("tempMinC",JSONWeather));
weather.setWeatherCode(getString("weatherCode",JSONWeather));
weather.setWeatherIconURL(getString("value",JSONIcon));
weather.setWinddir16point(getString("winddir16Point",JSONWeather));
weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
// For details of these operations and how each works go here:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
return dp;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
}

my program erase the first calculation and just put the last calculation into the array

I'm trying to calculate shortest path between user location to two destinations
and put the distance value into an array.
instead put all the calculation into the array, the result that i get in the array is only the distance from second destination. apparently my program erase the first calculation and after that start the next calculation. What should i correct so that my program does not erase the first calculation and put all the distance into the array ?
it should be like this :
distance1= distance from user locationA to LocationH
distance2= distance from user locationA to LocationI
add distance to distanArray
The result is distanArray=(distance1,distance2)
what i have now :
distanArray=(distance2)
This is my code
public class MainActivity extends FragmentActivity implements LocationListener {
TextView tvDistanceDuration;
TextView tvDistanceDuration2;
TextView tvDistanceDuration3;
private LocationManager locationManager;
private String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calcdistance);
tvDistanceDuration = (EditText) findViewById(R.id.editText1);
tvDistanceDuration2 = (EditText) findViewById(R.id.editText2);
tvDistanceDuration3 = (EditText) findViewById(R.id.editText3);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
else {
Toast.makeText( getApplicationContext(),
"Location not available",
Toast.LENGTH_LONG).show();
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the location listener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lon = (double) (location.getLongitude());
Location locationA = new Location("USER");
locationA.setLatitude(lat);
locationA.setLongitude(lon);
List<LatLng> pointss = new ArrayList<LatLng>();
List<LatLng> pointsss = new ArrayList<LatLng>();
Location locationH = new Location("Shelter 7");
locationH.setLatitude(-0.868101);
locationH.setLongitude(119.888341);
Location locationI = new Location("Shelter 8");
locationI.setLatitude(-0.900198);
locationI.setLongitude(119.88856);
LatLng des = new LatLng(locationA.getLatitude(), locationA.getLongitude());
LatLng des1 = new LatLng(locationH.getLatitude(), locationH.getLongitude());
LatLng des2 = new LatLng(locationI.getLatitude(), locationI.getLongitude());
pointss.add(des1);
pointss.add(des2);
pointsss.add(des);
tvDistanceDuration3.setText(String.valueOf(pointss));
for (int i = 0; i <(pointss.size()); i++) {
LatLng origin = pointsss.get(0);
LatLng dest = pointss.get(i);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
String distance = "";
String duration = "";
ArrayList<String> distan = new ArrayList<String>();
if(result.size()<1){
Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
points = new ArrayList<LatLng>();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
distan.add(distance);
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
String minDist = Collections.min(distan);
tvDistanceDuration.setText("Distance:"+minDist + ", Duration:"+duration);
tvDistanceDuration2.setText(String.valueOf(distan));
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}

Categories

Resources