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.
Related
I have a map fragment in my app with 2 kinds of markers: the ones that i added with the event OnMapLongClick() and the ones i added from a .csv file. I want to save some details about each coordinates from the marker by starting a new activity when i click on them. The issue that i have is that with the markers added from the .csv file, it always shows the position of the last marker. So my question is, how get i get the position of the corresponded marker that comes from the .csv when i click on it? Can this work by changing the ArrayList with Hashmap?
MapsActivity (the relevant code):
public void onMapLongClick(LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.title("Introdus!");
markerOptions.draggable(true);
mMap.addMarker(markerOptions);
mMap.setOnMarkerClickListener(this);
latlngNew = latLng;
LatLng latlngNew;
}
#Override
public boolean onMarkerClick(Marker marker) {
if (counter==0) {
openDialog();
}
else
{
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
counter--;
}
return false;
}
public void openDialog() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(R.string.default_info_title);
dialog.show();
Button bt_da = (Button) dialog.findViewById(R.id.dialog_ok);
Button bt_nu = (Button) dialog.findViewById(R.id.dialog_cancel);
bt_da.setOnClickListener(this);
bt_nu.setOnClickListener(this);
bt_nu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
}
);
bt_da.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
counter=1;
Intent intent = new Intent(MapsActivity.this, MainActivity.class);
intent.putExtra("markerLat", latlngNew.latitude);
intent.putExtra("markerLong", latlngNew.longitude);
startActivity(intent);
}
});
}
public void Upload(View view) throws IOException {
File file = new File(getExternalFilesDir(null), "date.csv");
if (file.exists()) {
InputStream instream = new FileInputStream(file);
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader reader = new BufferedReader(inputreader);
List<LatLng> latLngList = new ArrayList<LatLng>();
String line = " ";
while ((line = reader.readLine()) != null) // Read until end of file
{
double lat = Double.parseDouble(line.split(",")[0]);
double lon = Double.parseDouble(line.split(",")[1]);
latLngList.add(new LatLng(lat, lon));
mMap.setOnMarkerClickListener(this);
}
for (LatLng pos : latLngList) {
latlngNew=pos;
Marker m=mMap.addMarker(new MarkerOptions()
.position(pos)
.title("Din CSV!")
.draggable(true)
);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, DEFAULT_ZOOM));
}
}
else
{
Toast.makeText(MapsActivity.this,"Nu exista fisierul!", Toast.LENGTH_SHORT).show();
}
}
public void Sterge(View view){
mMap.clear();
}
}
That was because you pass to intent latlngNew coords:
intent.putExtra("markerLat", latlngNew.latitude);
intent.putExtra("markerLong", latlngNew.longitude);
which points to the last marker because of loop:
for (LatLng pos : latLngList) {
latlngNew=pos;
...
}
So, for passing to intent coords of selected marker you should modify openDialog() by adding LatLng parameter like openDialog(LatLng coords) and pass to openDialog(LatLng coords) coordinates of selected marker. Something like that:
public void openDialog(LatLng coords) {
//... your code without changes
bt_da.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
counter=1;
Intent intent = new Intent(MapsActivity.this, MainActivity.class);
// pass coords instead of latlngNew:
intent.putExtra("markerLat", coords.latitude);
intent.putExtra("markerLong", coords.longitude);
startActivity(intent);
}
});
}
and onMarkerClick() changed to
#Override
public boolean onMarkerClick(Marker marker) {
if (counter==0) {
// pass marker coordinates here:
openDialog(marker.getPosition());
}
else
{
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
counter--;
}
return false;
}
I have two activities in first activity, I have two text views fromLocation and toLocation. On click of from and to text view I am calling next activity in which I have a map and I choose a location which I am storing in string and showing on text view. This choose location I want to show on fromLocation text view of first activity onClick of a layout of useLocation in second activity on the basis of which text view is choose. If onClick of fromLocation the address should show on fromLocation text view and onClick of toLocation address should show on toLocation. This will be onResume method of first activity.
Now I am getting the address on both text views when I choose address for first time onClick on fromLocation text view.
How to do this..?
GoSendActivity(FirstActivity)
public class GoSend extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private GoogleMap mGoogleMap;
private MarkerOptions markerOptions;
private LinearLayout ll;
private TextView additionalContactFrom,additionalContactTo,txt_from,txt_to;
private LinearLayout linearLayoutFrom,linearLayoutTo;
private ImageView next;
private Toolbar toolbar;
private EditText locdetailsFrom,locdetailsTo,itemDetails;
private Intent i;
private LatLng currentLocation,curentpoint,center;
private GPSTracker gps;
double latitude,longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
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
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
public void setUI() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("COURIER");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
locdetailsFrom = (EditText) findViewById(R.id.editText_from_details);
locdetailsFrom.setText(GoSendData.instance.getmFromLocationDetails());
locdetailsTo = (EditText) findViewById(R.id.editText_to_details);
locdetailsTo.setText(GoSendData.instance.getmToLocationDetails());
itemDetails = (EditText) findViewById(R.id.editText_ItemDetail);
txt_from = (TextView) findViewById(R.id.Text_from);
txt_to = (TextView) findViewById(R.id.Text_to);
additionalContactFrom = (TextView) findViewById(R.id.contactDetailsFrom);
additionalContactTo = (TextView) findViewById(R.id.contactDetailsTo);
linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
linearLayoutTo = (LinearLayout) findViewById(R.id.LinearLayoutTo);
next = (ImageView) findViewById(R.id.imageView_next);
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
/// GoSendData.instance.addressType=0;
startActivity(i);
}
});
txt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
//GoSendData.instance.addressType=1;
startActivity(i);
}
});
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (linearLayoutFrom.getVisibility() == View.GONE) {
linearLayoutFrom.setVisibility(View.VISIBLE);
} else {
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
additionalContactTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (linearLayoutTo.getVisibility() == View.GONE) {
linearLayoutTo.setVisibility(View.VISIBLE);
} else {
linearLayoutTo.setVisibility(View.GONE);
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), GoSendDetailsActivity.class);
startActivity(i);
}
});
}
#Override
public void onResume() {
int LocationClick;
super.onResume(); // Always call the superclass method first
txt_from.setText(GoSendData.instance.mFromLocation);
txt_to.setText(GoSendData.instance.mToLocation);
}
private void setupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.addMarker(markerOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
setupMap();
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
ChooseFromMapActivity(second activity)
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center,curentpoint;
private LinearLayout markerLayout,useLocation;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude,longitude;
private GPSTracker gps;
Intent intent;
double x, y;
StringBuilder str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
SetUpUI();
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
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
startActivity(intent);
}
});
}
private void SetUpUI(){
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("CHOOSE FROM MAP");
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
GoSendData.instance.mFromLocation=addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ";
GoSendData.instance.mToLocation=addresses.get(0).getAddressLine(0)+addresses.get(0).getAddressLine(1)+"";
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
If i understand correctly.. You should launch second activity as startActivityForResult and after choosing location on map return it as a result.
The first activity should now this value from the method onActivityResult
http://developer.android.com/training/basics/intents/result.html
Click on first textview launch second activity with requestcode
Second activity after choosing location finishes with setResult, where you store chosen location
Get the result in onActivityResult of first activity and set it to textView
the same for second textview. Use different requestcodes for different textview, which you should check in onActivityResult to determine which textView data was chosen in second activity
So I wrote a class that will find the users location and find the distance between that and another point but I have a random number generator so when I call I use method I use in my activity (restarting the activity) the random number changes which I don't want to happen. If anyone would show me how to refresh the users location on the click of the button without restarting the whole activity it would be a great help
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
Random rand = new Random();
int n = rand.nextInt(5) + 1;
int score = 0;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
//contains lat and lon of another place
private void setUpMap() {
if (n == 1) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 2) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeSU, longitudeSU)).title("2"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 3) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeArtsBuilding, longitudeArtsBuilding)).title("3"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 4) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeJH, longitudeJH)).title("4"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 5) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeForebell, longitudeForebell)).title("5"); //create marker
mMap.addMarker(marker); // adding marker
}
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
//Refresh button. Will reset the location of your flag
//If the user clicks the button, the activity is finished and restarted
Button button2=(Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View w){
Intent intent = getIntent();
finish();
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
Note if there's a problem with the code I delete a lot of it so it's only brackets and stuff. I just posted all this so you have an idea what's happening. I only want to refresh your location, not the entire activity
Intent intent = getIntent();
finish();
startActivity(intent);
Can you try this one ? I did not test it.
MarkerOptions markerOptions;
Marker marker;
private void setUpMap() {
if(marker!= null)
marker.remove();
markerOptions = null;
if (n == 1) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
} else if (n == 2) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeSU, longitudeSU)).title("2"); //create marker
} else if (n == 3) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeArtsBuilding, longitudeArtsBuilding)).title("3"); //create marker
} else if (n == 4) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeJH, longitudeJH)).title("4"); //create marker
} else if (n == 5) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeForebell, longitudeForebell)).title("5"); //create marker
}
if(markerOptions!=null)
marker = mMap.addMarker(markerOptions); // adding marker
}
And on your onclicklistener
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View w){
n = rand.nextInt(5) + 1;
setUpMap();
}
});
Or you can use marker.setPosition(LatLng); if your marker is not null
I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
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
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Location class
public class Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
How can I achieve this?? Please help..
try this :
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}
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()]));