getting geolocation after 20 seconds - android

i am making an android app using geo-location in android. i am using the location manager for getting the geo-location coordinates.
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
and using the postDelayed() function for continuously called the getLastKnownLocation() for the geo-location. and set the interval timing 1000 (1 sec). but i get the response after 20 seconds.
Can any body explain me why it happens. i am new in android.

Note that you shouldn't be calling getLastKnownLocation() every second if you have a Location Listener set up (which it looks like you do). Just use the latest values given in the onLocationChanged() callback.
This code works for me, it registers a Location Listener, which updates the lat/lon member variables, and then the Runnable runs with an initial interval of one second, and then every five seconds (5000 milliseconds) and displays the most current location value.
I put in a Toast to make sure that the Runnable is being run every 5 seconds by handler.postDelayed().
Here is the full Activity code:
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements LocationListener {
LocationManager locationManager;
Handler handler;
Location location;
double latitude;
double longitude;
TextView lat;
TextView lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
handler.postDelayed(runLocation, 1000);
}
public Runnable runLocation = new Runnable(){
#Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Edit:
As an alternative, you could take out the use of postDelayed(), and just use the onLocationChanged() events.
In the example below, I used both NETWORK_PROVIDER and GPS_PROVIDER.
This is needed in the AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Here is the modified code, which registers the Activity as a Location Listener for both Network location callbacks and GPS location callbacks, with a minimum time interval of one second. Note that events can come in at a greater interval than one second, but with the GPS location enabled, I saw them coming in every second (it was taking longer with only Network location enabled).
public class MainActivity extends ActionBarActivity implements LocationListener {
LocationManager locationManager;
Handler handler;
Location location;
double latitude;
double longitude;
TextView lat;
TextView lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
//handler.postDelayed(runLocation, 1000);
}
/*
public Runnable runLocation = new Runnable(){
#Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location changed: " + latitude + " " + longitude, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

use google map api v2
example
public class MapActivity extends FragmentActivity {
protected GoogleMap map;
protected LatLng start;
protected LatLng end;
TextView tvDistance,tvTime;
CameraPosition mCameraPosition;
// LatLng currentLocation ;
Context context;
public static boolean loadMapChk = false;
double getlatitute, getlongitute;
String addressGeo;
/**
* This activity loads a map and then displays the route and pushpins on it.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
context = this;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
getlatitute = bundle.getDouble("getlatitute");
getlongitute = bundle.getDouble("getlongitute");
addressGeo = bundle.getString("addressGeo");
}
tvDistance = (TextView) findViewById(R.id.tvDistance);
tvTime = (TextView) findViewById(R.id.tvTime);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(myLocationChangeListener);
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange (Location location) {
LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());
// Toast.makeText(getApplicationContext(),"location.getLongitude()>>>>>>>"+location.getLongitude(),Toast.LENGTH_LONG).show();
// map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
Bitmap bitmapicon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.start_blue);
map.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude())).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(bitmapicon)));
if (!loadMapChk)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12.5f), 4000, null);
loadMapChk = true;
}
start = new LatLng(location.getLatitude(), location.getLongitude());
end = new LatLng(getlatitute, getlongitute);
Bitmap bitmapiconEnd = BitmapFactory.decodeResource(context.getResources(),
R.drawable.end_green);
map.addMarker(new MarkerOptions().position(
new LatLng(getlatitute, getlongitute)).title(addressGeo).icon(BitmapDescriptorFactory.fromBitmap(bitmapiconEnd)));
Routing routing = new Routing(Routing.TravelMode.DRIVING);
routing.registerListener(routingListener);
routing.execute(start, end);
}
};
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
loadMapChk = false;
}
public RoutingListener routingListener = new RoutingListener() {
#Override
public void onRoutingSuccess(PolylineOptions mPolyOptions, Route route) {
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(Color.CYAN);
polyOptions.width(8);
polyOptions.addAll(mPolyOptions.getPoints());
tvDistance.setText("Distance : "+route.getDistanceText());
tvTime.setText("Time : "+route.getDurationText());
// Toast.makeText(getApplicationContext(), "Distance : "+route.getDistanceText()+" & Time = "+route.getDurationText(),6).show();
map.addPolyline(polyOptions);
// Start marker
MarkerOptions options = new MarkerOptions();
// End marker
options = new MarkerOptions();
options.position(end);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green));
map.addMarker(options);
}
#Override
public void onRoutingStart() {
// TODO Auto-generated method stub
}
#Override
public void onRoutingFailure() {
// TODO Auto-generated method stub
}
};
}

Use timer handeller to implement delay.
Total time= Time delay+ Server response
You might be facing problem because of that

Related

Why does creating a loop on my button make my android app hang?

I am writing an Android location based app. For my app i need to store my current location for every fixed time period. I create a button to start store those location using loop, but in device it hangs when start. If i remove the loop, it works. Whats the problem?
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
Button btnStart,btnStop, btnstatus;
double fLat,fLon,sLat,sLon;
ArrayList<LatLng> locArray=new ArrayList<LatLng>();
int var,i;
double lat=0, lon=0;
LatLng fLL,sLL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart=(Button) findViewById(R.id.btnStart);
btnStop=(Button) findViewById(R.id.btnStop);
btnstatus=(Button) findViewById(R.id.btnStatus);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(i=1;;i++)
{
Location loc=googleMap.getMyLocation();
double lat=loc.getLatitude();
double lon=loc.getLongitude();
LatLng latLon=new LatLng(lat, lon);
locArray.add(latLon);
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(i=1;i<locArray.size();i++)
{
LatLng src=locArray.get(i-1);
LatLng dest=locArray.get(i);
googleMap.addPolyline(new PolylineOptions().add(new LatLng(src.latitude, src.longitude),new LatLng(dest.latitude, dest.longitude)).width(3).color(Color.RED).geodesic(true));
}
}
});
SupportMapFragment supportMapFragment=(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap=supportMapFragment.getMap();
//googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
googleMap.setMyLocationEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
Location loc=googleMap.getMyLocation();
double latitude=loc.getLatitude();
double longitude=loc.getLongitude();
LatLng latLon=new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLon));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLon));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#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
}
}
And here is my Button XML:
You have an endless for loop in the btnStart:
for (i = 1;; i++)
Why do you have a loop there? There is only one location anyway. Just remove the for loop and leave the internal code.
public void onClick(View v) {
Location loc = googleMap.getMyLocation();
double lat = loc.getLatitude();
double lon = loc.getLongitude();
LatLng latLon = new LatLng(lat, lon);
locArray.add(latLon);
}
your endless loop blocks UI thread will cause ANR :
for(i=1;;i++)
You can use single boolean variable to decide where to start and where to stop fetching the locations from providers
This is example, variable is isStartedFetching
private boolean isStartedFetching = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart=(Button) findViewById(R.id.btnStart);
btnStop=(Button) findViewById(R.id.btnStop);
btnstatus=(Button) findViewById(R.id.btnStatus);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isStartedFetching = true;
/* for(i=1;;i++) // this is infinite loop, so application will hang
{
Location loc=googleMap.getMyLocation();
double lat=loc.getLatitude();
double lon=loc.getLongitude();
LatLng latLon=new LatLng(lat, lon);
locArray.add(latLon);
}
} */
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isStartedFetching = false;
for(i=1;i<locArray.size();i++)
{
LatLng src=locArray.get(i-1);
LatLng dest=locArray.get(i);
googleMap.addPolyline(new PolylineOptions().add(new LatLng(src.latitude, src.longitude),new LatLng(dest.latitude, dest.longitude)).width(3).color(Color.RED).geodesic(true));
}
}
});
SupportMapFragment supportMapFragment=(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap=supportMapFragment.getMap();
//googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
googleMap.setMyLocationEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
if(isStartedFetching) {
Location loc=googleMap.getMyLocation();
double latitude=loc.getLatitude();
double longitude=loc.getLongitude();
LatLng latLon=new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLon));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLon));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
You haven't set the condition for quitting the loop.
for (i = 1; ; i++)
for loop is
for (initialize to start loop; condition to stop loop; increment/decrement) {
// body of loop
}
just because you haven't put the condition when to stop,
that's why you are getting an error.

Not getting location coordinates unless location has changed

Here is what I need to do. I need to launch my application and on the click of a button, I need to display the current coordinates, that is latitude and longitude. I followed this tutorial and used the following code for my purpose:
public class MainActivity extends Activity {
public double latitude;
public double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
final TextView latValueLabel = (TextView)findViewById(R.id.latLabel);
final TextView lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
(Copy pasted only a part of the code, please ignore any unclosed brackets or anything like that.)
It continuously gets the latitude longitude as location changes and stores it to two double variables latitude and longitude and when the setButton is clicked, it displays the last stored lat-lon value. That would be the user's current location. Now the issue is, I launched the app and while still staying on the exact location from which the app is launched, I clicked the Set Button. But at that time the location is not changed, so the latitude and longitude are displayed as zero, which is the default value of the double variables. I need to take a walk around with the device so that the location is changed before I can get my actual coordinates. How can I get the lat-lon as soon as the app is launched?
You can use getLastKnownLocation(...) to initialise the longitude and latitude values like this:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
This is your total class.
public class MainActivity extends Activity {
public double latitude;
public double longitude;
private TextView latValueLabel,lonValueLabel ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
latValueLabel = (TextView)findViewById(R.id.latLabel);
lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}

Null pointer errors when using fragments

The GPS class and MainActivity both worked fine until we tried to add a second page. We've tried using intents and fragments and have spent way too many hours/days on trying to figure this out.
We keep getting NullPointerExceptions for either the onClickListener() in MainActivity and when updating any textviews from the GPS class. We know it has something to do with how the fragments work but we're not sure how to fix this.
This is our MainActivity class
public class MainActivity extends ActionBarActivity {
// Get buttons and text fields
public Button showLocation;
// TextViews
public static TextView showLatitude;
public static TextView showLongitude;
public static TextView showDistance;
// GPS class
GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
showLocation = (Button) findViewById(R.id.btnShowLocation);
showLatitude = (TextView) findViewById(R.id.txtLatitude);
showLongitude = (TextView) findViewById(R.id.txtLongitude);
showDistance = (TextView) findViewById(R.id.txtDisplayDistance);
// Create gps
gps = new GPS(MainActivity.this);
// show location button click event
showLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
gps.setTotalDistance(0.0);
}
});//END LISTENER
}// END ONCREATE
public void nextPage(View view) {
// In response to button
Intent intent = new Intent(this, ResourcePage.class);
// Set activity intent
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And this is the GPS class
public class GPS extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS/Network/Location status
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
// Location Class
Location location;
// Latitude and longitude save points
private double startLatitude = 0;
private double endLatitude = 1.0;
private double startLongitude = 0;
private double endLongitude = 1.0;
private double totalDistance = 0;
// Results Array
private float[] results = new float[1];
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_FOR_UPDATES = 10; // meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BETWEEN_UPDATES = 1000; // 1 second
// Location Manager
protected LocationManager locationManager;
// Interface
public GPS(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Checking Flags
if (!isGPSEnabled && !isNetworkEnabled) {
// ^no network provider is enabled do nothing/go on^
}
else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
} //END OF LAST IF BLOCK
} //END OF SECOND IF BLOCK
} //END OF "FIRST" IF BLOCK
// if GPS Enabled get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
}
}
}
}
}//END OF ELSE BLOCK
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
// Call to remove updates from listener
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPS.this);
}
}
public double getLatitude(){
if(location != null){
startLatitude = location.getLatitude();
}
// Return latitude
return startLatitude;
}
public double getLongitude(){
if(location != null){
startLongitude = location.getLongitude();
}
// Return longitude
return startLongitude;
}
//Function to check GPS/wifi are enabled
public boolean canGetLocation() {
//return boolean
return this.canGetLocation;
}
// Function to show settings alert dialog if gps is off
public void showSettingsAlert(){
// On pressing Settings button will launch Settings Options
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Settings button listener/press
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
// Called from listener on gps change of X
#Override
public void onLocationChanged(Location location) {
//Display Latitude and Longitude
if(location != null){
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
MainActivity.showLatitude.setText(String.valueOf(startLatitude));
MainActivity.showLongitude.setText(String.valueOf(startLongitude));
}
// Get distance between
Location.distanceBetween(startLatitude, startLongitude, endLatitude,endLongitude, results);
// Convert to miles Add distance to total
totalDistance = totalDistance + results[0] * 0.000621371192;
// Display the total
MainActivity.showDistance.setText(String.format("%.2f", totalDistance));
// Move old values to End locations
endLatitude = startLatitude;
endLongitude = startLongitude;
}
// Function to clear total distance (Testing)
public void setTotalDistance(Double savedData){
totalDistance = savedData;
MainActivity.showDistance.setText(String.valueOf(totalDistance));
}
public double getTotalDistance(){
return totalDistance;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
For the layout files we have activity_main.xml which is empty, fragment_main.xml which has all our text fields and buttons and then fragment_resource.xml which has nothing but a textview so we knew things would appear on it.
If you say all your views belong to the fragment then initialize views in fragment not in Activity.
The Activity layout does not have the views and findViewById looks for a view in the current inflated layout. So the initialization fails leading to NullPointerException when you use the view objects.
TextView showLatitude;
TextView showLongitude;
TextView showDistance;
GPS gps;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
showLocation = (Button)rootView.findViewById(R.id.btnShowLocation);
showLatitude = (TextView) rootView.findViewById(R.id.txtLatitude);
showLongitude = (TextView) rootView.findViewById(R.id.txtLongitude);
showDistance = (TextView) rootView.findViewById(R.id.txtDisplayDistance);
gps = new GPS(getActivity()); // wrong bind the service to the activtiy
showLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
gps.setTotalDistance(0.0); // remove this
}
});
return rootView;
}
Also you have
public class GPS extends Service
Its a Service class. You need to bind the service to Activity. But you dogps = new GPS(getActivity());
Replace this:
setContentView(R.layout.activity_main);
By:
setContentView(R.layout.fragment_main);
You have the problem in this method
public void setTotalDistance(Double savedData){
totalDistance = savedData;
MainActivity.showDistance.setText(String.valueOf(totalDistance));
}
You can't just call the MainActivity that way it will return NULL
Pointer exception for showDistance Variable.Because its not a static
class.So you want to do like this.
public void setTotalDistance(Double savedData){
totalDistance = savedData;
((this.mContext)MainActivity).showDistance.setText(String.valueOf(totalDistance));
}
Surely this will make some sense.

Arcgis : how to get device location

Hie i tried to implement this codes in my application but it doesnt work , i dont know where i went wrong.
basically, when i launch the sample of the device location. it doesnt show me where is my current location and i dont see any blue dots that resembles the current location i am at.
the only thing that i see is the map . just a plain zoom out map.
I would be really thankful if someone who could help me out on how to get the current location with the blue dots that is displayed on the map..
this is my MainActivity.class
public class HelloWorld extends Activity {
MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
mMapView = (MapView) findViewById(R.id.map);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"));
mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
public void onStatusChanged(Object source, STATUS status) {
if (source == mMapView && status == STATUS.INITIALIZED) {
LocationService ls = mMapView.getLocationService();
ls.setAutoPan(false);
ls.start();
}
}
});
}
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
}
this is a code that draws my location every 1 second via provider and GPS .
let's first declare variables :
private GraphicsLayer myGraphicalLayer;
MapView mMapView;
ArcGISLocalTiledLayer baseLayer;
private LocationManager mlocManager;
private LocationListener mlocListener;
in onCreate function WE CALL LocationListener:
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mlocListener);
// loading the map
mMapView = (MapView) findViewById(R.id.localMap);
baseLayer = new ArcGISLocalTiledLayer(basemapurl);
mMapView.addLayer(baseLayer);
// defining my position layer
myGraphicalLayer = new GraphicsLayer();
then a function to draw my location :
private void SetMyLocationPoint(final double x, final double y) {
PictureMarkerSymbol myPin = new PictureMarkerSymbol(getResources().getDrawable(
R.drawable.mylocation_icon));
Point wgspoint = new Point(x, y);
Point mapPoint = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326),
mMapView.getSpatialReference());
Graphic myPinGraphic = new Graphic(mapPoint, myPin);
try {
myGraphicalLayer.removeAll();
} catch (Exception e) {
e.printStackTrace();
}
myGraphicalLayer.addGraphic(myPinGraphic);
myGraphicalLayer.setVisible(true);
mMapView.addLayer(myGraphicalLayer);
}
make internal class that implements MyLocationListener to get you instant location, and let it call the function named SetMyLocationPoint like this way :
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
SetMyLocationPoint(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "provider enabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "provider disabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
You need to use your own location manager or the location client to get the device's current location and then you will have to add that point on the map.
Your map should be in a MapFragment.
Get the googleMap object from the fragment and then add your custom blue dot on it.
LocationManager locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
The above code gets you the location in onLocationChanged method.
Note: i have used GPS_PROVIDER to get the location.
There are other ways to get the current location too.

Print Longitude and Latitude in textbox Android

I have looked about and cannot find any direct threads regarding what I am looking for. I am trying to create an Android application which dials out an emergency number at the push of a button (which I have got working) but cannot get the location (displayed in Longitude and Latitude) to display, I have tried doing it with Toast and EditText boxes. I am new to Android development so wanted to start with something easy, but the LongLat part is being troublesome. Any help would be greatly appreciated.
Below is the code I have been tampering with in order to try and get it to grab the Long and Lat, then in another file I have been trying to use a click listener to assign it to a button so when the button is pressed (in main.xml) it will display the Long and Lat either in a textfield or in toast.
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Context;
import android.location.LocationManager;
import android.location.Criteria;
public class EmergencyLocation extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView);
longitudeField = (TextView) findViewById(R.id.long_lat);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialise the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
private void TextView() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#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
}}
First, you need to set up a LocationManager:
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// set preferred provider based on the best accuracy possible
Criteria fineAccuracyCriteria = new Criteria();
fineAccuracyCriteria.setAccuracy(Criteria.ACCURACY_FINE);
String preferredProvider = manager.getBestProvider(fineAccuracyCriteria, true);
Now, you have to create a LocationListener. In this case, it calls the method updateLocation():
LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location) {
// called when a new location is found by the network location provider.
updateLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
EDIT:
Then, you have to register the listener with your LocationManager (and try to get the cached location):
manager.requestLocationUpdates(preferredProvider, 0, 0, listener);
// get a fast fix - cached version
updateLocation(manager.getLastKnownLocation());
And finally, the updateLocation() method:
private void updateLocation(Location location) {
if (location == null)
return;
// save location details
latitude = (float) location.getLatitude();
longitude = (float) location.getLongitude();
}
EDIT2:
OK, just saw your code. In order to make it work, just move around a few bits:
/** Called when the activity is first created. **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView);
longitudeField = (TextView) findViewById(R.id.long_lat);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);
}
#Override
protected void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
Hope it helps!
Quite easy. I use the locationListener as an attribute inside a Location class. Here's how I do it:
package com.rifsoft.android.helper.location;
import com.rifsoft.android.helper.IListener;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class Location implements IListener
{
public final static int IDX_LATITIDE = 0;
public final static int IDX_LONGITUDE = 1;
private double[] lastLocation = {0.0, 0.0};
private LocationManager locationManager = null;
private ILocation activity = null;
private LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(android.location.Location location)
{
// TODO: http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate
lastLocation[IDX_LATITIDE] = location.getLatitude();
lastLocation[IDX_LONGITUDE] = location.getLongitude();
activity.onLocationChange();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
/**
* Constructor, needs LocationManager
* #param activity Activity that will receive the notification when location has changed
* #param locationManager LocationManager
*/
public Location(final ILocation act, LocationManager lm) throws LocationException
{
if (lm == null)
{
throw new LocationException(LocationException.ERR_NULL_LOCATION_MANAGER);
}
if (act == null)
{
throw new LocationException(LocationException.ERR_NULL_ILOCATION);
}
locationManager = lm;
activity = act;
registerListener();
android.location.Location lastCachedLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastCachedLocation != null)
{
lastLocation[IDX_LATITIDE] = lastCachedLocation.getLatitude();
lastLocation[IDX_LONGITUDE] = lastCachedLocation.getLatitude();
}
}
/**
* Retuns last known most accurate location as latitude, longitude
* #return Latitude, Longitude
*/
public double[] getLastLocation()
{
return lastLocation;
}
#Override
public void registerListener()
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
public void unRegisterListener()
{
locationManager.removeUpdates(locationListener);
}
}
Then the activity.onLocationChange() goes like
public void onLocationChange()
{
locationUpdated = true;
double[] coordinates = location.getLastLocation();
EditText lon = (EditText) activity.findViewById(R.id.longitude_value);
lon.setText(String.valueOf(coordinates[Location.IDX_LONGITUDE]));
EditText lat = (EditText) activity.findViewById(R.id.latitude_value);
lat.setText(String.valueOf(coordinates[Location.IDX_LATITIDE]));
}

Categories

Resources