I am writing a program, in which i have to show calculated distance between two locations, from current location to destination location, and to get that i have written a method which calculates total distance between locations, now the main point is i am not getting distance value in TextView.
and here is my code, please check below:
LocationsActivity.java:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(LocationsActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("locations");
Log.d("jarray", jarray.toString());
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
locations = new Locations();
locations.setName(object.getString("name"));
locations.setLatitude(object.getString("latitude"));
locations.setLongitude(object.getString("longitude"));
actorsList.add(locations);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
public void distanceBetweenTwoLocations() {
Location currentLocation = new Location("");
currentLocation.setLatitude(latitude);
currentLocation.setLongitude(longitude);
for (int i = 0; i < actorsList.size(); i++) {
Location destinationLocation = new Location(" ");
destinationLocation.setLatitude(Double.valueOf(actorsList.get(i).getLatitude()));
destinationLocation.setLongitude(Double.valueOf(actorsList.get(i).getLongitude()));
double inMeters = currentLocation.distanceTo(destinationLocation);
double totalDistance = inMeters / 1000;
locations.setDistance(totalDistance + "");
}
}
}
}
Problem is with your distanceBetweenTwoLocations() method.
you are adding location data in actorsList at doInBackground method while you are retrieving data from locationsList
Still same mistake with your getView method. you are adding data in Locations list while in getView you are fetching data from locationsList
Updated :
you are passing actorsList to the adapter while you are assigning distance to the locations list.
Check with Following Code :
you need to call the following method at onPostExecute before notifying adapter adapter.notifyDataSetChanged();
public void distanceBetweenTwoLocations() {
Location currentLocation = new Location("");
currentLocation.setLatitude(latitude);
currentLocation.setLongitude(longitude);
for (int i = 0; i < actorsList.size(); i++) {
Locations mLocations = (Locations) actorList.get(i);
Location destinationLocation = new Location(" ");
destinationLocation.setLatitude(Double.valueOf(actorsList.get(i).getLatitude()));
destinationLocation.setLongitude(Double.valueOf(actorsList.get(i).getLongitude()));
double inMeters = currentLocation.distanceTo(destinationLocation);
double totalDistance = inMeters / 1000;
mLocations.setDistance(totalDistance + "");
}
}
}
Related
Whenever I am trying to remove an object from JsonArray , It shows there is no such method exists. My target API version is 8. I look up for other questions regarding this but could not find a suitable solution. please help me with this.
class JSONAsync extends AsyncTask<String, Void, JSONArray>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = Util.setProgressDialog(Activity.this, "Please Wait",
"loading....", false);
progressDialog.show();
}
#Override
protected JSONArray doInBackground(String... urls)
{
try
{
HttpGet httppost = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200)
{
HttpEntity entity = response.getEntity();
String resString = EntityUtils.toString(entity);
JSONObject jso= new JSONObject(resString);
JSONArray jsono= jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsono);
for (int i = 0; i < jsono.length(); i++) {
if (jsono.getJSONObject(i).getString("jobName").equals(null) || jsono.getJSONObject(i).getString("jobName").equals("null") || jsono.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsono.getJSONObject(i).getString("jobName"));
jsono.remove(i);
}
}
if(jsono.length()>=0)
{
jobname = new String[(jsono.length())];
jobid = new String[(jsono.length())];
for(int i=0;i<jsono.length();i++)
{
JSONObject js = jsono.getJSONObject(i);
Log.e("Name : ", jsono.getJSONObject(i).getString("jobName"));
jobname[i] = jsono.getJSONObject(i).getString("jobName");
Log.e("Id : ", jsono.getJSONObject(i).getString("jobId"));
jobid[i] = jsono.getJSONObject(i).getString("jobId");
}
return jsono;
}
else
{
Toast.makeText(getApplicationContext(), "No Workers available : "+ logedinUserId , Toast.LENGTH_LONG).show();
return null;
}
}
} catch (IOException e)
{
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result)
{
progressDialog.dismiss();
}
}
Do you really want a headache supporting a bit amount of so old devices?
Nevertheless, use this:
JSONObject jso= new JSONObject(resString);
JSONArray jsonArray = jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsonArray);
ArrayList<Integer> i_ar = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.getJSONObject(i).getString("jobName").equals(null) || jsonArray.getJSONObject(i).getString("jobName").equals("null") || jsonArray.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsonArray.getJSONObject(i).getString("jobName"));
i_ar.add(i);
}
}
JSONArray jsono = new JSONArray();
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i_ar.indexOf(i) == -1)
{
list.put(jsonArray.get(i));
}
}
}
if(jsono.length()>=0)
{
//.... continue...
In this activity, i get places nearby and add them to a listview. I wanted also to add the place's phone number in an arrayList like the other datas, so i had to use place details request. So, i get all the place_id for all the places from the arrayList and launch the query to get the details (phone number). The problem is in class "readFromGooglePlaceDetailsAPI", it goes in the "try" and goes out with nothing happening, i don't know why!!! I only can see "IN TRY !!!" and then "----" from the println.
Is my sequence not right?
Where is the problem and what is the solution ?
public class ListActivity extends Activity implements OnItemClickListener {
public ArrayList<GetterSetter> myArrayList;
ArrayList<GetterSetter> detailsArrayList;
ListView myList;
ProgressDialog dialog;
TextView nodata;
CustomAdapter adapter;
GetterSetter addValues;
GetterSetter addDetails;
private LocationManager locMan;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_activity);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.placesList);
placeSearch();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void placeSearch() {
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
dialog = ProgressDialog.show(this, "", "Please wait", true);
//build places query string
String placesSearchStr;
placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types="+ ServicesListActivity.types+
"&key=My_KEY";
//execute query
new readFromGooglePlaceAPI().execute(placesSearchStr);
myList.setOnItemClickListener(this);
}
public void detailsSearch() {
String detailsSearchStr;
//build places query string
for(int i=0; i < myArrayList.size(); i++){
detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + myArrayList.get(i).getPlace_id() +
"&key=My_KEY";
Log.d("PlaceID:", myArrayList.get(i).getPlace_id());
//execute query
new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr);
}
}
public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
detailsArrayList = new ArrayList<GetterSetter>();
String phoneNumber =" -NA-";
try {
System.out.println("IN TRY !!!");
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("result");
System.out.println("Before FOR !!!");
for (int i = 0; i < results.length(); i++) {
System.out.println("IN FOR LOOP !!!");
addDetails = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
if(!arrayItems.isNull("formatted_phone_number")){
phoneNumber = arrayItems.getString("formatted_phone_number");
Log.d("Phone Number ", phoneNumber);
}
addDetails.setPhoneNumber(phoneNumber);
System.out.println("ADDED !!!");
detailsArrayList.add(addDetails);
Log.d("Before", detailsArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("------------------------------------------------------------------");
Log.d("After:", detailsArrayList.toString());
// nodata = (TextView) findViewById(R.id.nodata);
//nodata.setVisibility(View.GONE);
// adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList);
// myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
// dialog.dismiss();
}
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
String rating=" -NA-";
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
addValues = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
//place ID for place details later
String placeID = arrayItems.getString("place_id").toString();
if(!arrayItems.isNull("rating")){
rating = arrayItems.getString("rating");
}
addValues.setPlace_id(placeID);
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(rating);
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
//Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
// System.out
// .println("############################################################################");
// Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
dialog.dismiss();
detailsSearch();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(ListActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber());
startActivity(details);
}
}
try{
JSONObject jsonObject = new JSONObject(str);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
//your logic here
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Note that the getJSONArray() function throws an Exception if the mapping fails. For example I can't find a JSON Array which is called results.
The most important thing you have to do at first is:
change:
catch (Exception e) {
}
to
catch (Exception e) {
Log.e(YOUR_TAG, "Exception ..." , e);
}
Your try throws an Exception which you don't even Log. That might be the reason why you are confused.
In my app I want to show the multiple marker using latitude and longitude from JSON but when I run the application it only shows one marker, other markers are not shown. Please help - here is my code:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(title); // set title
progressDialog.setMessage(message); // set message
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Loading...", "Please wait for few seconds");
// dialog = new ProgressDialog(getActivity().this);
// dialog.setMessage("Loading, please wait");
// dialog.setTitle("Connecting server");
// dialog.show();
// dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// Date a = new Date();
// a.setTime(System.currentTimeMillis()-(60*60*1000));
// Log.e("onehourback",""+a);*/
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("SingleIMEs");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Log.e("object",""+object);
/*try {
array.add(jarray.getJSONObject(i));
Log.e("array",""+array);
} catch (JSONException e)
{
e.printStackTrace();
}*/
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
}
}
//}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
/* adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
*/
}
}
private void setUpMapIfNeeded(View inflatedView) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(latt,lng)).title("eee"));
Log.e("lat",""+latt);
Log.e("lon",""+lng);
mMap.setMyLocationEnabled(true);
if (mMap != null) {
//setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("WePOP"));
// mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position( new LatLng(Double.parseDouble(datas.get("Lat")), Double.parseDouble(datas.get("Long")))));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
It looks like you're overwriting your latt and lng variables multiple times in this code:
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
I would suggest you create a List that holds some sort of object containing latt and lng information (something like List positions).
Then modify your code in setUpMapIfNeeded to cycle through all your LatLngs. Something like this:
for(LatLng latlng: positions) {
mMap.addMarker(new MarkerOptions().position(new LatLng(latlng.getLat(),latlng.getLng())).title("eee"));
Log.e("Added marker at lat: " + latlng.getLat() + ", lng: " + latlng.getLng());
}
Notice: It's been quite some time since i've used android and google maps, so the code i've written here probably isn't perfect - but the idea should be good :-)
I have an issue, which is not that big, but to the user it is bad.
The app basically gets the user's input of some place and, when the user clicks on the button, a URL to the Google API with the place on its parameter is sent to an AsyncTask, where it sends this URL via HttpGet and is returned a JSONArray with everything needed. The problem is, when I click on the button and the internet is not that good, the button seems to "freeze" like this:
My activity code is below:
public class MainActivity extends Activity{
...
protected void onCreate(Bundle savedInstanceState){...}
public void onResume()}
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
try{
List<Location> locations = new SearchTask(MainActivity.this).execute(strSearch).get();
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
...
}
}
}
}
}
}
My AsyncTask class code is below:
public class SearchTask extends AsyncTask<String, Void, List<Location>>{
...
protected List<Location> doInBackground(String... params){
if(isNetworkAvailable()){
HttpGet httpGet = null;
HttpClient client = null;
HttpResponse response = null;
StringBuilder builder = null;
try{
String param = URLDecoder.decode(params[0], "UTF-8").replace(" ", "%20");
httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?address=" + param + "&sensor=false");
client = new DefaultHttpClient();
builder = new StringBuilder();
}
catch(UnsupportedEncodingException e){
Log.i("Error", e.getMessage());
}
try{
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int val;
while((val = br.read()) != -1){
builder.append((char) val);
}
}
catch(IOException e){
Log.i("Error", e.getMessage());
}
JSONObject jsonObject = new JSONObject();
List<Location> listLocation = new ArrayList<Location>();
int countJson = 0;
try{
jsonObject = new JSONObject(builder.toString());
JSONArray jArray = jsonObject.getJSONArray("results");
countJson = jArray.length();
for(int i = 0; i < countJson; i++){
Location location = new Location();
String formattedAddress = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getString("formatted_address");
double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
location.setFormattedAddress(formattedAddress);
location.setLat(lat);
location.setLng(lng);
listLocation.add(location);
}
}
catch(JSONException e){
Log.i("Error", e.getMessage());
}
return listLocation;
}
else{
return null;
}
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progress = new ProgressDialog(context);
progress.setMessage("Loading...");
progress.show();
}
#Override
protected void onPostExecute(List<Location> result){
super.onPostExecute();
progress.dismiss();
}
private boolean isNetworkAvailable(){
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connManager.getActiveNetworkInfo();
return info != null && info.isConnected();
}
}
The ListView is on the same xml of the EditView and the Button.
Is there a way to improve it in order to make the UI not behave like this?
Thanks!
Try this:
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
new SearchTask(MainActivity.this).execute(strSearch);
}
}
#Override
protected void onPostExecute(List<Location> locations){
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
}
progress.dismiss();
}
In my app it's possibile to insert markers with touch and then it's possible to calculate the path through these markers with subsequent HTTP requests.
The issue is that very often the first markers is skipped and between the last two markers is drawn a segment too.
Here's the code:
public class MultipleTracksDrawer extends AbstractDrawer {
private static final String TAG_LOG = MultipleTracksAsyncTask.class.getName();
private boolean flag = false;
void draw() {
for(int i = 0; i < markers.size() - 1; i++) {
Marker firstMarker = markers.get(i);
Marker secondMarker = markers.get(i + 1);
//I extract latitude and longitude from the markers
LatLng firstLatLng = new LatLng(firstMarker.getPosition().latitude, firstMarker.getPosition().longitude);
LatLng secondLatLng = new LatLng(secondMarker.getPosition().latitude, secondMarker.getPosition().longitude);
//Url for the request
String URL = Utilities.getInstance().makeURL(firstLatLng.latitude, firstLatLng.longitude,
secondLatLng.latitude, secondLatLng.longitude, travelMode);
//At the end of the markers list i set the flag as true for draw the path
if(i == markers.size() - 2) {
flag = true;
}
MultipleTracksAsyncTask multipleTracksAsyncTask = new MultipleTracksAsyncTask(URL);
multipleTracksAsyncTask.execute();
}
}
private class MultipleTracksAsyncTask extends AsyncTask<Void,Void,String> {
private ProgressDialog mDialog;
private String URL;
public MultipleTracksAsyncTask(String URL) {
this.URL = URL;
}
protected void onPreExecute() {
mDialog = ProgressDialog.show(context, "", "Loading...", true);
}
protected void onPostExecute(String result) {
if(mDialog != null) {
if(mDialog.isShowing()) {
mDialog.dismiss();
}
}
if(result != null) {
parseJSON(result);
//I draw the path only if the flag is true
if(flag) {
drawPath();
}
}
}
public String doInBackground(Void... param) {
JSONRequest jParser = new JSONRequest();
String json = jParser.getJSONFromUrl(URL,connectionTimeout,dataTimeout);
return json;
}
}
private void parseJSON(String result) {
try {
final JSONObject json = new JSONObject(result);
//I get "routes" array
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONArray legsArray = routes.getJSONArray("legs");
JSONObject legsObject = legsArray.getJSONObject(0);
//I get distance and duration of the path
JSONObject distance = legsObject.getJSONObject("distance");
JSONObject duration = legsObject.getJSONObject("duration");
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
//Decoding
model.getMarkersTrack().addAll(Utilities.getInstance().decodePoly(encodedString));
mTrackDistance += distance.getInt("value");
mTrackDuration += duration.getInt("value");
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "The path is not available", Toast.LENGTH_SHORT).show();
}
}
private void drawPath() {
for(int i = 0; i < model.getMarkersTrack().size() - 1; i++) {
LatLng src = model.getMarkersTrack().get(i);
LatLng dest = model.getMarkersTrack().get(i + 1);
PolylineOptions polylineOptions = new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(5)
.color(Color.BLUE).geodesic(true);
Polyline polyline = googleMap.addPolyline(polylineOptions);
//I save the polylines
model.getTrackPolylines().add(polyline);
}
}
}
I put here the code for the HTTP request too:
public class JSONRequest {
private InputStream is = null;
private String json = "";
/**
* Method that makes the HTTP request
*
* #param url URL of the HTTP request
* #param connectionTimeout timeout for the connection
* #param dataTimeout timeout for the download
* #return
*/
public String getJSONFromUrl(String url, int connectionTimeout, int dataTimeout) {
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,connectionTimeout);
HttpConnectionParams.setSoTimeout(httpParams, dataTimeout);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
//GET request
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
//I get the response
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
//I read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
}
Here's a picture: http://imageshack.com/a/img835/504/m0fc.png
UPDATE:
Problem fixed!
Now i create a new String URL in the draw() method of MultipleTracksDrawer class and i give it to the AsyncTask (as input parameter). In this way it works. I edited the code.