How to get my location? [duplicate] - java

This question already has answers here:
How to calculate distance between two locations using their longitude and latitude value
(14 answers)
Closed 5 years ago.
I am new with maps in android i have this code :
enter codepublic class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback {
private GoogleMap mMap;
Button req_button;
String[] lat;
String[] lon;
String[] id;
String[] emails;
double latitude,lonitude;
int result_search,StatusChange_customer;
String params_search ,Status_cheked_customer,params_checked_customer,Status_cheked_customer_rating;
public Handler mHandler;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Intent intent1 = getIntent();
lat = intent1.getStringArrayExtra("latitute");
lon = intent1.getStringArrayExtra("longitude");
id = intent1.getStringArrayExtra("id");
emails = intent1.getStringArrayExtra("emails");
latitude=intent1.getDoubleExtra("MyLat",0);
lonitude=intent1.getDoubleExtra("MyLon",0);
req_button =(Button)findViewById(R.id.R_id);
this.mHandler = new Handler();
this.mHandler.postDelayed(m_Runnable,5000);
}
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
Search_for_Accepted_Job();
Toast.makeText(MapsActivity.this,"in runnable",Toast.LENGTH_SHORT).show();
MapsActivity.this.mHandler.postDelayed(m_Runnable, 10000);
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng [] sydeny = new LatLng[lat.length];
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// Add a marker in Sydney and move the camera
for (int i=0 ; i< lat.length;i++) {
sydeny[i] = new LatLng(Double.parseDouble(lat[i]), Double.parseDouble(lon[i]));
}
for (int i=0 ; i< sydeny.length;i++) {
mMap.addMarker(new MarkerOptions().position(sydeny[i]).title(emails[i]+ " " + id[i]));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny[i], 5));
}
LatLng sydeny1 = new LatLng(latitude,lonitude);
mMap.addMarker(new MarkerOptions().position(sydeny1).title("Your location" ));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny1, 5));*/
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
public void Request(View view) {
Toast.makeText(this," Request",Toast.LENGTH_SHORT).show();
for (int i=0; i< lat.length;i++)
{
send_request(id[i]);
}
req_button.setEnabled(false);
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
lonitude=location.getLatitude();
lonitude=location.getLongitude();
}
So this code take a latitude and longitude from another activity and present them in Map , recently i tried to implement two interfaces
(GoogleMap.OnMyLocationButtonClickListener
GoogleMap.OnMyLocationClickListener)
and i get my location with blue circle in map and change at real time with me and there is a method named
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
my Question is how to use the latitude and longitude of this method , i mean how to get the latitude and longitude of my location because it is correct i i will need it to calculate the distance between me and other places .

To correctly use location in your app, you need to handle asking user permission to turn on location in settings (in case it is turned off) and then follow the steps in the documentation:
https://developer.android.com/training/location/retrieve-current.html
To answer your question exactly, did you try location.getLatitude() and location.getLongitude()?

Related

LatLng.latitude and LatLng.longitude cant be used because not specific values

got an error at line "Location.distanceBetween(LatLng.latitude, LatLng.longitude, circle.getCenter().latitude,circle.getCenter().longitude,distance);" LatLng.latitude and LatLng.longitude cant be used because not specific values.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{//DirectionFinderListener {
private GoogleMap mMap;
//private Button btnFindPath;
//private EditText etOrigin;
//private EditText etDestination;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
// private List<Marker> = new ArrayList<>();
Circle shape;
Marker marker;
//private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
long minDistance = 15;
float[] distance = new float[2];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//btnFindPath = (Button) findViewById(R.id.btnFindPath);
//etOrigin = (EditText) findViewById(R.id.etOrigin);
//etDestination = (EditText) findViewById(R.id.etDestination);
/*btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});*/
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng hcmus = new LatLng(3.719639, 103.123972); //3.719639, 103.123972
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("IBM CoE")
.position(hcmus)));
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(3.719639, 103.123972))
.radius(10000)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
Location.distanceBetween(LatLng.latitude, LatLng.longitude, circle.getCenter().latitude,circle.getCenter().longitude,distance);
if ( distance[0] <= circle.getRadius())
{
Toast.makeText(this, "You are in radius location", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "You are not in radius location", Toast.LENGTH_LONG).show();
}
/*if (destinationMarkers == ) { //equation
Intent main = new Intent(MapsActivity.this, MainActivity.class);
startActivity(main);
}
else { Toast.makeText(this, "You are not in radius location", Toast.LENGTH_LONG).show();
}*/
}
How to get current Location latitude and longitude
See the parameter of doc of distanceBetween method. It results distance in meter between two locations and it takes parameters like this,
startLatitude double: the starting latitude
startLongitude double: the starting longitude
endLatitude double: the ending latitude
endLongitude double: the ending longitude
results float: an array of floats to hold the results
As its clearly stated, the first two parameters hold the value of first location object's Latitude and Longitude. In your case, you're referring the default Location object's Latitude and Longitude properties which doesn't represent any location value.
I can see you're already getting current location
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
So, this line should be like this,
Location.distanceBetween(latitude, longitude, circle.getCenter().latitude,circle.getCenter().longitude, distance);

Passing object list to another activity

In my code I am creating an area object by placing markers on map and taking its values from user then storing it in a list. Then I used parcelableArrayList to pass this list to another activity. What I want is that user presses displayArea button only then this activity is launched and list is displayed in AllAreas activty. But my app crashes whenever I click that button
Code for mapActivity
public class MainActivity extends
FragmentActivity implements View.OnClickListener,MapDropdown.DialogListener {
public static final String mapLongitude="longitude";
public static final String mapLatitude="latitude";
FragmentManager fm = getSupportFragmentManager();
Button displayareas;
Switch deleteareas;
private boolean del = false;
private int set = 0;
public ArrayList<Area> areas;
private GoogleMap newmap; // Might be null if Google Play services APK is not available.
LatLng m;
float radius;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayareas = (Button) findViewById(R.id.display);
displayareas.setOnClickListener(this);
deleteareas = (Switch) findViewById(R.id.delete);
areas = new ArrayList<Area>();
deleteareas.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
del = true;
Toast.makeText(getApplicationContext(), "Deleting enabled", Toast.LENGTH_LONG).show();
} else {
del = false;
Toast.makeText(getApplicationContext(), "Deleting disabled", Toast.LENGTH_LONG).show();
}
}
});
Log.d("Map","MapCreated");
setUpMapIfNeeded();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.display) {
Intent intent = new Intent(getApplicationContext(),AllAreas.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", areas);
intent.putExtras(bundle);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
//setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (newmap == null) {
// Try to obtain the map from the SupportMapFragment.
newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (newmap != null) {
setUpMap();
Log.d("MAPS","Map working");
}
else Log.d("MAPS","not working");
}
}
private void setUpMap() {
newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
newmap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
newmap.animateCamera(CameraUpdateFactory.zoomTo(20));
newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location"));
Log.d("LATITUDE",String.valueOf(latitude));
Log.d("LONGITUDE",String.valueOf(longitude));
GoogleMap.OnMarkerClickListener listener = new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
if(del == false){
m=marker.getPosition();
MapDropdown dFragment = new MapDropdown();
// Show DialogFragment
dFragment.show(fm, "Dialog Fragment");}
else if(del == true){
marker.remove();
}
return true;
}
};
newmap.setOnMarkerClickListener(listener);
newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Animating to the touched position
newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
Marker mmarker = newmap.addMarker(markerOptions);
m = latLng;
Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));
Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDialogPositiveClick(DialogFragment dialog , String s, String n){
Log.d("Button","positive");
Log.d("Name",n);
Log.d("Radius",s);
Log.d("On press LATITUDE",String.valueOf(m.latitude));
Log.d("On press LONGITUDE",String.valueOf(m.longitude));
Area newarea = new Area(n,m.latitude,m.longitude,Float.valueOf(s));
Log.d("object",newarea.getId());
Log.d("object",newarea.getName());
areas.add(newarea);
areas.get(0);
Log.d("areas",areas.get(0).getName());
}
#Override
public void onDialogNegativeClick(DialogFragment dialog){
Log.d("Button","negative");
}
}
Part of mainActivity.java adding to list is
#Override
public void onDialogPositiveClick(DialogFragment dialog , String s,
String n){
Log.d("Button","positive");
//areas is list name
//m is current marker
Area newarea = new Area(n,m.latitude,m.longitude,Float.valueOf(s));
areas.add(newarea);
}
And of passing list in mainactivity is
public void onClick(View v) {
//id of button that will launch Allareas activity
if (v.getId() == R.id.display) {
Intent intent = new Intent(getApplicationContext(),AllAreas.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", areas);
intent.putExtras(bundle);
startActivity(intent);
}
}
for AllAreas class
public class AllAreas extends ActionBarActivity {
//initial layout
private Area a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.areas);
Bundle bundle = getIntent().getExtras();
ArrayList<Area> arealist = bundle.getParcelableArrayList("mylist");
if (arealist.isEmpty()) {
Log.d("area list lala", "is empty");
}
else {
for (int i = 0; i < arealist.size(); i++) {
a = arealist.get(0);
Log.d("area list lala", a.getName());
}
}
}
}
You are getting it with wrong key.you used the key "data" for putting it into bundle and trying to get it by the key "mylist"
bundle.putParcelableArrayList("data", areas);
change the line
ArrayList<Area> arealist = bundle.getParcelableArrayList("mylist");
to
ArrayList<Area> arealist = bundle.getParcelableArrayList("data");
let me know if it works.

GoogleMaps API can't get current latitude and longitude

I'm trying to get the coordinates but without success. The result is 0 . But when I write:
googleMap.setMyLocationEnabled(true);
I can see the blue dot. I'm trying to get these values with this code:
lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();
After that, lat and lng are 0.
My whole code:
public class GPS_maps extends Activity {
// Google Map
private GoogleMap googleMap;
static Location currentLocation;
static double lat , lng;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
coordinates = (TextView) findViewById(R.id.txt_coordinates);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// googleMap.setMyLocationEnabled(true);
lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();
coordinates.setText(String.valueOf(lat) +" , " +String.valueOf(lng));
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
googleMap.animateCamera(yourLocation);
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}}
}
I don't get any errors. Where is my mistake?
Try the following:
Remove static modifier from the declaration of lat, lan.
Make sure you are sending in the correct syntax to setCoordiante.
To make sure the lat and lan are right, print them out right after you get them.

Can't get coordinates using LocationManager

I'm developing an app that uses the Google Maps V2 API and I'm having trouble do get my coordinates and to put it into the LatLng object... Here's my code:
public class TelaMapa extends android.support.v4.app.FragmentActivity
implements OnMapClickListener, OnCameraChangeListener{
// Google Map
protected GoogleMap googleMap;
private SupportMapFragment mapFragment;
protected AndroidLocationSource locationSource;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_mapa);
}
#Override
protected void onResume(){
super.onResume();
configureMap();
}
/**
* function to load map. If map is not created it will create it for you
* */
private void configureMap() {
if (googleMap == null) {
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
LocationManager LM = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String bestProvider = LM.getBestProvider(new Criteria(),true);
Location localAtu;
/*Location myLocation = LM.getLastKnownLocation(bestProvider);
double lat= myLocation.getLatitude();
double lng = myLocation.getLongitude();
LatLng latLng = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));*/
if(bestProvider != null){
localAtu = LM.getLastKnownLocation(bestProvider);
} else {
localAtu = LM.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
LatLng latLng;
if(localAtu != null){
latLng = new LatLng(localAtu.getLatitude(), localAtu.getLongitude());
final CameraPosition position = new CameraPosition.Builder()
.target(latLng)
.bearing(0)
.tilt(0)
.zoom(17)
.build();
CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
googleMap.moveCamera(update);
adicionarMarcador(googleMap, latLng);
locationSource = new AndroidLocationSource();
googleMap.setLocationSource(locationSource);
locationSource.setLocation(latLng);
} else {
Toast.makeText(getApplicationContext(),
"GPS desligado ou indisponível!", Toast.LENGTH_LONG)
.show();
}
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Desculpe! Não foi possível criar o mapa!", Toast.LENGTH_SHORT)
.show();
}
}
}
That's it, I installed it in my Motorola Atrix and it always show me the toast in the else
block... Thanks for reading!
Answered by Sanket Kachhela!
Just use this tutorial and it will work fine!
androidhive.info/2012/07/android-gps-location-manager-tutorial

How to plot on maps from arraylist with lon/lat?

This is my Map Class...
public class Mapa extends FragmentActivity implements LocationListener {
public GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
Getting Google Play availability status
int status =GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else {
Getting reference to the SupportMapFragment
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
Getting GoogleMap object from the fragment
map = fm.getMap();
Enabling MyLocation Layer of Google Map
map.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
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
Getting latitude of the current location
double latitude = location.getLatitude();
Getting longitude of the current location
double longitude = location.getLongitude();
Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(15));
Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
And this is my class with the arraylist
public void getPontos(View view) {
String codigo;
codigo = linhaList.get(spinner.getSelectedItemPosition()).getCodigo();
new WebServiceGetPontosLinha().execute(codigo);
}
private class WebServiceGetPontosLinha extends
AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "",
getResources().getText(R.string.connecting), true, false);
}
#Override
protected Void doInBackground(String... params) {
WebServiceConsumer webServiceConsumer = new WebServiceConsumer(
MainActivity.this);
pontoList = webServiceConsumer.getPontos(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
pontoArrayAdapter = new ArrayAdapter<PontosLinhas>(
MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, pontoList);
spinner1.setAdapter(pontoArrayAdapter);
}
}
How do I plot the content of spinner on maps like an image?
This involves a lot of details which is not needed for your but hope you get the picture.
I developed an app that among other things shows the location of hydrants on a map and this is how I load the hydrants to the map:
private class LoadHydrantsToMapTask extends
AsyncTask<Hydrant, Integer, List<MarkerOptions>> {
private int loadHydrantsGoal = 0;
public LoadHydrantsToMapTask(int loadHydrantsGoal) {
this.loadHydrantsGoal = loadHydrantsGoal;
}
// Before running code in separate thread
#Override
protected void onPreExecute() {
Device.lockOrientation((Activity)context);
// Create a new progress dialog.
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal bar .
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage(context
.getString(R.string.adding_hydrants));
// This dialog can't be canceled by pressing the back key.
progressDialog.setCancelable(false);
// This dialog isn't indeterminate.
progressDialog.setIndeterminate(false);
// The maximum number of progress items is 100.
progressDialog.setMax(loadHydrantsGoal);
// Set the current progress to zero.
progressDialog.setProgress(0);
// Display the progress dialog.
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected List<MarkerOptions> doInBackground(Hydrant... hydrants) {
List<MarkerOptions> markers = new ArrayList<MarkerOptions>();
for (Hydrant hydrant : hydrants) {
final String hydrant_type = hydrant.getHydrantType();
final String hydrant_icon_path = hydrant.getIconPath();
double latitude = hydrant.getLatitude();
double longitude = hydrant.getLongitude();
final LatLng position = new LatLng(latitude, longitude);
final String address = hydrant.getAddress();
final String addressNumber = hydrant.getAddressNumber();
final String addressremark = hydrant.getAddressRemark();
final String remark = hydrant.getRemark();
BitmapDescriptor icon = BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED);
if (!hydrant_icon_path.isEmpty()) {
File iconfile = new File(hydrant_icon_path);
if (iconfile.exists()) {
BitmapDescriptor loaded_icon = BitmapDescriptorFactory
.fromPath(hydrant_icon_path);
if (loaded_icon != null) {
icon = loaded_icon;
} else {
Log.e(TAG, "loaded_icon was null");
}
} else {
Log.e(TAG, "iconfile did not exist: "
+ hydrant_icon_path);
}
} else {
Log.e(TAG, "iconpath was empty on hydrant type: "
+ hydrant_type);
}
StringBuffer snippet = new StringBuffer();
if (!address.isEmpty())
snippet.append("\n" + address + " " + addressNumber);
if (addressremark.isEmpty())
snippet.append("\n" + addressremark);
if (!remark.isEmpty())
snippet.append("\n" + remark);
markers.add(new MarkerOptions().position(position)
.title(hydrant_type).snippet(snippet.toString())
.icon(icon));
publishProgress(markers.size());
}
return markers;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
// after executing the code in the thread
#Override
protected void onPostExecute(List<MarkerOptions> markers) {
GoogleMap map = GoogleMapsModule.getInstance().getMap();
for (MarkerOptions marker : markers) {
if (marker != null)
map.addMarker(marker);
}
if (markers.size() == mHydrants.size()) {
setAllHydrantAdded(true);
setNearbyHydrantsAdded(true);
} else {
setNearbyHydrantsAdded(true);
}
Device.releaseOrientation((Activity) context);
}
}
When I call the task, I have a list of Hydrant objects. To parse the list to the AsyncTask I convert the list into an Array:
new LoadHydrantsToMapTask(hydrants.size()).execute(hydrants
.toArray(new Hydrant[hydrants.size()]));

Categories