Progress Dialog location listener - java

Within my programme i have a location listner used with the GPS to gain the user current lat/long points.
I want to implement a progress Dialog whilst the GPS gains the co-ordinates.
Currently I call the progressDialog within the onCreate() method then when my location object is nolonger null, then i dismess the progressdialog.
Sadly at the moment the dialog does not show at all.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
***** Call a new progress dialog object when the locationManager is gaining lat/long*****
d = ProgressDialog.show(this, "GPS Posistion", "Gaining GPS posistion...", false, true);
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
***** Once lat/long is found, dismiss the progress dialog*****
d.dismiss();
Double latToPass = location.getLatitude();
Double longToPass = location.getLongitude();
locationManager.removeUpdates(locationListener);
locationManager = null;
Intent changesStart = new Intent("com.example.flybaseapp.PassLatLong");
changesStart.putExtra("passedLat", latToPass);
changesStart.putExtra("passedLong", longToPass);
startActivity(changesStart);
}
}

Use AsyncTask
Double latToPass;
Double longToPass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncAction().execute(null, null, null);
}
private class AsyncAction extends AsyncTask<String, Void, String> {
public boolean status = false;
private ProgressDialog pd;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
status = true;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
Intent changesStart = new Intent("com.example.flybaseapp.PassLatLong");
changesStart.putExtra("passedLat", latToPass);
changesStart.putExtra("passedLong", longToPass);
startActivity(changesStart);
}
}
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
latToPass = location.getLatitude();
longToPass = location.getLongitude();
locationManager.removeUpdates(locationListener);
//locationManager = null;
}
}

Related

How to call a condition on a view?

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

How can I send current location from one activity to another?

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

onLocationChanged() isn't working properly

I'm trying to track users position and draw a path/his route on a map according to his movement (updatePolyline(), updateCamera(), updateMarker() are responsible for drawing a route). Program compiles, but the crucial error is that onLocationChanged() isn't called when location actually changes, thus, no path is beeing drawn.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private PolylineOptions mPolylineOptions;
LocationManager locationManager;
private LatLng mLatLng;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
// if(location != null) {
//
// onLocationChanged(location);
// }
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, this);
}
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
mLatLng = new LatLng(latitude, longitude);
runOnUiThread(new Runnable() {
#Override
public void run() {
updatePolyline();
updateCamera();
updateMarker();
}
});
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
initializeMap();
}
private void updatePolyline() {
mMap.clear();
mMap.addPolyline(mPolylineOptions.add(mLatLng));
}
private void updateMarker() {
mMap.addMarker(new MarkerOptions().position(mLatLng));
}
private void updateCamera() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
}
private void initializeMap() {
mPolylineOptions = new PolylineOptions();
mPolylineOptions.color(Color.BLUE).width(10);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
LocationManager lm = null;
boolean gps_enabled = false, network_enabled = false;
if (lm == null)
lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MapsActivity.this);
dialog
.setTitle("No gps")
.setPositiveButton("Atšaukti", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
})
.setNegativeButton("Open settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MapsActivity.this.startActivity(myIntent);
}
});
AlertDialog alert_dialog = dialog.create();
alert_dialog.show();
}
return false;
}
});
}
}
}

Showing my track with Google map api v2 in android

I am trying to make an app that will show my current location and will track me from there with a line.I have been using Google maps Api v2 for android so i was trying to work with polylines to help me show my tracks but its not showing.
Can anyone help me with that..Thankyou.
Total code is provided.
public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener,
OnMyLocationButtonClickListener, OnClickListener, android.location.LocationListener {
private GoogleMap mMap;
private LocationClient mLocationClient;
private TextView mMessageView;
private boolean setIt;
// These settings are the same as the settings for the map. They will in fact give you updates
// at the maximal rates currently possible.
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_demo);
mMessageView = (TextView) findViewById(R.id.message_text);
Button b1=(Button)findViewById(R.id.start);
Button b2=(Button)findViewById(R.id.stop);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.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) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
getApplicationContext(),
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
/**
* Button to get current Location. This demonstrates how to get the current Location as required
* without needing to register a LocationListener.
*/
public void showMyLocation(View view) {
if (mLocationClient != null && mLocationClient.isConnected()) {
String msg = "Location = " + mLocationClient.getLastLocation();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (v.getId() == R.id.start) {
setIt = true;
};
if (v.getId() == R.id.stop) {
mMap.clear();
};
}
PolylineOptions rectOptions = new PolylineOptions().width(3).color(
Color.RED);
#Override
public void onLocationChanged(Location location) {
mMessageView.setText("Location = " + location);
rectOptions.add(new LatLng(location.getLatitude(), location.getLongitude()));
if (setIt == true){
mMap.addPolyline(rectOptions);
}
}
#Override
public void onConnected(Bundle connectionHint) {
mLocationClient.requestLocationUpdates(
REQUEST,
this); // LocationListener
}
/**
* Callback called when disconnected from GCore. Implementation of {#link ConnectionCallbacks}.
*/
#Override
public void onDisconnected() {
// Do nothing
}
/**
* Implementation of {#link OnConnectionFailedListener}.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
{
setIt = true;
};
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
#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
}
}
This is very easy to in Google Map API V2 . If you would like to do this then you can follow this reference link:
Go this stackoverflow link
This man already give useful solution. I have done the same way as this site told.
For your facility I have written the main things:
1.create a list of LatLng points such as:
List<LatLng> routePoints;
2.Add the route points to the list (could/should be done in a loop):
routePoints.add(mapPoint);
3.Create a Polyline and feed it the list of LatLng points as such:
Polyline route = map.addPolyline(new PolylineOptions()
.width(_strokeWidth)
.color(_pathColor)
.geodesic(true)
.zIndex(z));
route.setPoints(routePoints);
Try this and give feedback!!!

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