How we can send latitude and longitude to MySQL using Android? - android

Currently I am working with a project to get current latitude and longitude, I got that. Now I want the latitude and longitude send to MySQL database using Android. HTTP part of this program is not working.
LocationManager locationManager;
String mprovider;
String lat="", lon="";
private String Tag="MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postData(lat, lon);
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider, 0, 0, this);
if (location != null) {
onLocationChanged(location);
} else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}
private void postData(String la, String lo) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost htget = new HttpPost("http://192.168.1.2/yy.php/"+la+"/"+lo);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(htget);
String resp = response.getStatusLine().toString();
Toast.makeText(this, resp, Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.textView2);
tv.setText("Your Location is:" + lat + "--" + lon);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}

you can send data form android to server over http. here is more details

Use mysql's spatial extensions.
For making tables and using it with Google Maps api refer this:
Using MySQL and PHP with Google Maps
Before you start, I have few questions:
Which version of gmaps API are you working with?
How are you parsing the map marker (lat. long.) data?
How are you triggering the save (lat long/ map marker data event).
Workable method: create a JSON parser for parsing the Marker data (which is the JSON Object here).
public class MarkerJSONParser {
/** gets a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jMarkers = null;
try {
/** gets all the elements in the 'markers' array */
jMarkers = jObject.getJSONArray("markers");
} catch (JSONException e) {
e.printStackTrace();
}
/** enjoining getMarkers with the array of json object
* here each JSON object is a marker
*/
return getMarkers(jMarkers);
}
private List<HashMap<String, String>> getMarkers(JSONArray jMarkers){
int markersCount = jMarkers.length();
List<HashMap<String, String>> markersList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> marker = null;
/** Parsing and adding each marker to the list object */
for(int i=0; i<markersCount;i++){
try {
/** Call getMarker with marker JSON object to parse the marker */
marker = getMarker((JSONObject)jMarkers.get(i));
markersList.add(marker);
}catch (JSONException e){
e.printStackTrace();
}
}
return markersList;
}
/** Parsing the Marker JSON object */
private HashMap<String, String> getMarker(JSONObject jMarker){
HashMap<String, String> marker = new HashMap<String, String>();
String lat = "-NA-";
String lng ="-NA-";
try {
// Latitude extraction
if(!jMarker.isNull("lat")){
lat = jMarker.getString("lat");
}
// Longitude extraction
if(!jMarker.isNull("lng")){
lng = jMarker.getString("lng");
}
marker.put("lat", lat);
marker.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return marker;
}
}
Paste this in your MySQL's MainActivity.java:
// enjoining OnClick Event listener for the GoogleMap
mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latlng) {
addMarker(latlng);
sendToServer(latlng);
}
});
// enjoining location retrieval
new RetrieveTask().execute();
}
// Marking lat. long. on the GoogleMaps
private void addMarker(LatLng latlng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title(latlng.latitude + "," + latlng.longitude);
mGoogleMap.addMarker(markerOptions);
}
// Enjoining bg thread to save marker inMySQL server
private void sendToServer(LatLng latlng) {
new SaveTask().execute(latlng);
}
// bg thread to save the marker in MySQL server
private class SaveTask extends AsyncTask<LatLng, Void, Void> {
#Override
protected Void doInBackground(LatLng... params) {
String lat = Double.toString(params[0].latitude);
String lng = Double.toString(params[0].longitude);
String strUrl = "http://www.yourserverurllocation.com";
URL url = null;
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
connection.getOutputStream());
outputStreamWriter.write("lat=" + lat + "&lng="+lng);
outputStreamWriter.flush();
outputStreamWriter.close();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

Related

My UI is blocked using AsyncTask with distancematrix and google Maps

I'm using google maps to show some markers. The markers are download from a database and, at the same time, I get the distancematrix from google api, between the current position of the user and the marker that I get from the database.
My problem is that I was doing this with .get, bloking my ui (I've read that .get blocked the ui:
dataFromAsyncTask = testAsyncTask.get();
Now, I'm trying to do the same without blocking the ui, but I'm not be able to get at the same time, or in a good way, the distance for this markers.
I appreciate some help, please.
This is my code with my old and wrong .get:
for (City city : listCity.getData()) {
geoPoint = city.getLocation();
nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
startRetrievenDistanceAndDuration();
try {
dataFromAsyncTask = testAsyncTask.get();
} catch (InterruptedException i) {
} catch (ExecutionException e) {
}
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameCity)
.snippet(dataFromAsyncTask)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
startRetrievenDistanceAndDuration method:
private void startRetrievenDistanceAndDuration() {
final String url;
testAsyncTask = new DistanceBetweenLocations(new FragmentCallback() {
#Override
public void onTaskDone(String result) {
}
});
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";
testAsyncTask.execute(new String[]{url});
}
public interface FragmentCallback {
public void onTaskDone(String result);
AsyncTask class:
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url=new URL(params[0]);
}catch (MalformedURLException m){
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
}catch (IOException e){}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
}catch (IOException e){
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
return distance + ", " + duration;
}
#Override
protected void onPostExecute(String result) {
mFragmentCallback.onTaskDone(result);
}
}
I'm trying to do this, but I only show the last marker of my list:
Call in the loop the method:
startRetrievenDistanceAndDuration();
And in onTaskDone try to put the marker, but only get the last marker of my list
#Override
public void onTaskDone(String result) {
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(result)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
UPDATED AFTER CHANGES: (still don't work)
I can parse the data in Asynctask and send it in onPostExecute, but I only get one value, and not the 9 values that I have....
MAIN ACTIVITY:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(HashMap<String, String> result) {
super.onPostExecute(result);
String name = result.get("beachName");
String distance = result.get("distance");
String duration = result.get("duration");
String latitue = result.get("latitude");
String longitude = result.get("longitude");
Double mlatituDouble = Double.parseDouble(latitue);
Double mlongitudeDouble = Double.parseDouble(longitude);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
Toast.makeText(getActivity(), "mMap NO null", Toast.LENGTH_SHORT).show();
mMap.addMarker(new MarkerOptions().position(new LatLng(mlatituDouble, mlongitudeDouble))
.title(name)
.snippet(distance + " " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
ASYNCTASK CLASS:.
public class DistanceBetweenLocations extends AsyncTask<String, String, HashMap<String, String>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
HashMap<String, String> map;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected HashMap<String, String> doInBackground(String... params) {
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
map = new HashMap<String, String>();
map.put("beachName", nameBeach);
map.put("distance", distance);
map.put("duration", duration);
map.put("latitude", latitude);
map.put("longitude", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return map;
}
}
I'll use your last code (the "UPDATED AFTER CHANGES"), ok?
If I get it right, your DistanceBetweenLocations result will be a list of beaches geolocation data. So, on every iteration of the for loop in doInBackground, you are replacing the value of "map" variable, this is your problem.
To solve your problem, you can have a List of HashMap or a List of a Pojo like this:
public class BeachPojo {
private String beachName;
private String distance;
private String duration;
private String latitude;
private String longitude;
public String getBeachName() {
return beachName;
}
public void setBeachName(String beachName) {
this.beachName = beachName;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
Using the Pojo, your AsyncTask will be like this:
public class DistanceBetweenLocations extends AsyncTask<String, String, List<BeachPojo>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected List<BeachPojo> doInBackground(String... params) {
List<BeachPojo> list = new ArrayList<BeachPojo>();
BeachPojo pojo;
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
pojo = new BeachPojo();
pojo.setBeachName(nameBeach);
pojo.setDistance(distance);
pojo.setDuration(duration);
pojo.setLatitude(latitude);
pojo.setLongitude(longitude);
list.add(pojo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return list;
}
}
Now you have a List to iterate. I have adjusted the code a little bit to this goal:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(List<BeachPojo> result) {
super.onPostExecute(result);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
}
Double beachLatitude;
Double beachLongitude;
for (BeachPojo pojo : result) {
beachLatitude = Double.parseDouble(pojo.getLatitude());
beachLongitude = Double.parseDouble(pojo.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(beachLatitude, beachLongitude))
.title(pojo.getBeachName())
.snippet(pojo.getDistance() + " " + pojo.getDuration())
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
I hope you understand the idea of returning a List from your AsyncTask and loop throught the result on onPostExecute method.
Note: this is an implementation without knowing the real code, then you should adjust to your reality.
I'm not exactly sure what you're trying to do but I think you've made this more complicated then it has to be.
From what I understand you have a list of City objects and you use them to construct some URLs from which you retrieve a JSON object that is use to construct MarkerOptions objects.
You can do that using a AsyncTask like this:
public class Task extends AsyncTask<City, Void, Markers> {
String currentLatitude;
String currentlongitude;
public Task(String currentLatitude, String currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected String doInBackground(City... cities) {
final Markers mMap = ...;
for (City city : cities) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint != null) {
String latitude = String.valueOf(geoPoint.getLatitude());
String longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";);
urlConnection = (HttpURLConnection) url.openConnection();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString()).getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0);
String duration = jsonObject.getJSONObject("duration").getString("text");
String distance = jsonObject.getJSONObject("distance").getString("text");
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(distance + ", " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (urlConnection != null) {
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return mMap;
}
}
And here is how you can use this task.
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
Task task = new Task(currentLatitude, currentlongitude){
#Override
protected void onPostExecute(Markers markers) {
super.onPostExecute(markers);
//This runs on the UI thread and "markers" is the "mMap" object that was create on the background thread.
}
};
List<City> cities = ....
task.execute(cities.toArray(new City[cities.size()]));
}
}
The idea is that you need to execute all the long running operation in the AsyncTask's doInBackground(...) method. Also, you don't need to create other objects to deal with the AsyncTask response, you can override the task's onPostExecute(...) inside the class you've created the task in.

Android location listener does not work on some devices

I need to find user location in android. As I do not want to use GPS, I tried below code to find user location based on his/her Network, this works on some devices but not on all of them, what is the problem? is it becuase of Android version or something like hardware issues?
private double x, y;
private LocationManager lm;
lm = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, locationListenerNetwork);
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
x = location.getLatitude();
y = location.getLongitude();
lm.removeUpdates(this);
Geocoder gcd = new Geocoder(getActivity(), Locale.getDefault());
List<Address> addresses;
addresses = gcd.getFromLocation(x, y, 1);
city = addresses.get(0).getLocality();
}
Try this
give latitude and longitude in FetchLocationTask class
latitude = 27.003434;
longitude = 23.458569;
new FetchLocationTask(getActivity(), latitude, longitude).execute();
public class FetchLocationTask extends AsyncTask<Void, Void, Void> {
public Context context;
// private ProgressDialog mProgressDialog;
public String addressUrl;
public BufferedReader in;
public FetchLocationTask(Context context, double lat, double longi) {
this.context = context;
addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + longi + "&sensor=true";
}
#Override
protected void onPreExecute() {
}
/**
* Call the webservice and parse the data from the service in
* background.
*/
#Override
protected Void doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();// Client
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(addressUrl));
HttpResponse response = httpClient.execute(getRequest);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page);
if (jsonObject.has("results")) {
JSONArray jsonArray = (JSONArray) jsonObject.get("results");
if (jsonArray.length() > 0) {
jsonObject = (JSONObject) jsonArray.get(0);
if (jsonObject.has("formatted_address")) {
address = (String) jsonObject.get("formatted_address");
}
}
return null;
}
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* onPostExecute method after called webService and Set the data into
* adapter after background task is complete.
*/
#Override
protected void onPostExecute(Void result) {
if (address != null && address.length() > 0) {
Log.i("map", "My:::" + address);
etx_address.setText(address.toString());
}
}
}

Google map App is crashing 2 ways: 1) if there is no internet connection, 2) if gps is not enabled

Following is my code:
public class DetailDescription extends FragmentActivity implements LocationListener{
private static String TAG="DetailDescription";
GoogleMap mGoogleMap;
ArrayList<LatLng> mMarkerPoints;
double mLatitude=0;
double mLongitude=0;
private final static int DETAILS_TRUE=1;
private final static int DETAILS_FALSE=2;
private final static int DETAILS_ERROR=3;int position;
ConnectionDetector cd;GPSTracker gps;Boolean isInternetPresent = false;
protected void onCreate(Bundle savedInstanceState) {
cd = new ConnectionDetector(getApplicationContext());
ImageView imageview;
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
setContentView(R.layout.detaildescription);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(DetailDescription.this, "No Internet Connection",
"You don't have internet connection.", false);
}
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header);
position=getIntent().getIntExtra("position", 0);
SharedData.pos1=position;
TextView txtHeader=(TextView)findViewById(R.id.txtHeader);
txtHeader.setText(SharedData.mAtm[position].name);
TextView adress=(TextView)findViewById(R.id.adress);
adress.setText(SharedData.mAtm[position].address);
Button btnBack=(Button)findViewById(R.id.btnBack);
btnBack.setVisibility(View.VISIBLE);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlacesList.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
ImageButton btnNext=(ImageButton)findViewById(R.id.btnNext);
btnNext.setVisibility(View.VISIBLE);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlaceFinder.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
locationn();
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_launcher: R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
private void locationn() {
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Initializing
mMarkerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
mGoogleMap = fm.getMap();
// Enable MyLocation Button in the Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
else
{
Toast.makeText(DetailDescription.this, "Location can't be retrieved", 5000).show();
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
LatLng startPoint = new LatLng(mLatitude, mLongitude);
drawMarker(startPoint);
LatLng origin = mMarkerPoints.get(0);
LatLng dest = new LatLng(SharedData.mAtm[SharedData.pos1].lat, SharedData.mAtm[SharedData.pos1].lon);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
Marker marker= mGoogleMap.addMarker(new MarkerOptions().position(dest).title(SharedData.mAtm[position].address).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker1)));
marker.showInfoWindow();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
// TODO Auto-generated method stub
}
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="+SharedData.mAtm[SharedData.pos1].lat+","+SharedData.mAtm[SharedData.pos1].lon;
// 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;
}
/** A class to download data from Google Directions URL */
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 Directions 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;
// 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);
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);
}
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
}
private void drawMarker(LatLng point){
mMarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(mMarkerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(mMarkerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mGoogleMap.addMarker(options);
}
#Override
public void onLocationChanged(Location location) {
// Draw the marker, if destination location is not set
if(mMarkerPoints.size() < 2){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng point = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
drawMarker(point);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Change your condition flow this way,
public class DetailDescription extends FragmentActivity implements LocationListener
{
private static String TAG="DetailDescription";
GoogleMap mGoogleMap;
ArrayList<LatLng> mMarkerPoints;
double mLatitude=0;
double mLongitude=0;
private final static int DETAILS_TRUE=1;
private final static int DETAILS_FALSE=2;
private final static int DETAILS_ERROR=3;int position;
ConnectionDetector cd;GPSTracker gps;Boolean isInternetPresent = false;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
cd = new ConnectionDetector(getApplicationContext());
ImageView imageview;
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
isInternetPresent = cd.isConnectingToInternet();
if ( !isInternetPresent)
{
showAlertDialog(DetailDescription.this, "No Internet Connection",
"You don't have internet connection.", false);
}
else
{
setContentView(R.layout.detaildescription);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header);
position=getIntent().getIntExtra("position", 0);
SharedData.pos1=position;
TextView txtHeader=(TextView)findViewById(R.id.txtHeader);
txtHeader.setText(SharedData.mAtm[position].name);
TextView adress=(TextView)findViewById(R.id.adress);
adress.setText(SharedData.mAtm[position].address);
Button btnBack=(Button)findViewById(R.id.btnBack);
btnBack.setVisibility(View.VISIBLE);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlacesList.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
ImageButton btnNext=(ImageButton)findViewById(R.id.btnNext);
btnNext.setVisibility(View.VISIBLE);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlaceFinder.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
locationn();
}
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_launcher: R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
private void locationn() {
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Initializing
mMarkerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
mGoogleMap = fm.getMap();
// Enable MyLocation Button in the Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
else
{
Toast.makeText(DetailDescription.this, "Location can't be retrieved", 5000).show();
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
LatLng startPoint = new LatLng(mLatitude, mLongitude);
drawMarker(startPoint);
LatLng origin = mMarkerPoints.get(0);
LatLng dest = new LatLng(SharedData.mAtm[SharedData.pos1].lat, SharedData.mAtm[SharedData.pos1].lon);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
Marker marker= mGoogleMap.addMarker(new MarkerOptions().position(dest).title(SharedData.mAtm[position].address).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker1)));
marker.showInfoWindow();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
// TODO Auto-generated method stub
}
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="+SharedData.mAtm[SharedData.pos1].lat+","+SharedData.mAtm[SharedData.pos1].lon;
// 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;
}
/** A class to download data from Google Directions URL */
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 Directions 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;
// 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);
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);
}
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
}
private void drawMarker(LatLng point){
mMarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(mMarkerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(mMarkerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mGoogleMap.addMarker(options);
}
#Override
public void onLocationChanged(Location location) {
// Draw the marker, if destination location is not set
if(mMarkerPoints.size() < 2){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng point = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
drawMarker(point);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

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
}
}

Update Maps based on Spinner value

I have successfully made an activity that shows nearby places. Now I have to retrieve Maps based on spinner value and show the default world map if no value is selected from the spinner. Say I have a spinner in the action bar of an activity, and it consists of various city names, and if I chose New York from the spinner, the map of New York appears in the Map Screen Area. If possible, can Anyone guide me how to do this and also if possible, tell me how to show the famous tourist locations of that city. I have not found any beneficial tutorial on this. Any help would be appreciated.
My NearbyPlacesActivity.java
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//gps tracker and connnection detect to be included
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
}
}
}
//location listener functions
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
#Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(Location givenlocation){
//get location manager
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
#SuppressWarnings("deprecation")
String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true"+
"&types="+encodedstr+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc);
}
}
#Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
This is how, you may implement your spinner listener
yourpinner.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
you may check this and this for additional reference

Categories

Resources