Getting approximate user location - android

locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
t= (TextView)findViewById(R.id.textView);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
double lat = lastKnownLocation.getLatitude();
double lon = lastKnownLocation.getLongitude();
t.setText(""+lat+""+lon);
}
});
This is my code and I'm trying to get approximate location of user. But i don't know why i'm getting null object reference exception. Is this the right way of doing? can anyone help me with getting user location with network? Should I add request location updates method to get last known location?

Related

Fused Location Api Get time from GPS

I have an application that tracks users location.
My application uses FusedLocationApi , Google new way of getting device location using Google Play Services.
Provider of locations that i give from GPS is labeled as fused.
Because of application users may change device time, it is important to get real time from GPS.
Problem is that when i try to get time from Location object , it returns device time not GPS time.
Any solutions to get GPS time in this situation are appreciated.
private Location mLastLocation;
public void onConnected(Bundle arg0) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
public void onLocationChanged(Location location) {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Date date = new Date(mLastLocation.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String time = dateFormat.format(date)
}
To get GPS UTC, do it in normal way:
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
// not LocationManager.NETWORK_PROVIDER
#Override
public void onLocationChanged(Location location)
{
long utc = location.getTime();
// ....
}

Android Location Manager returning NULL

I have a simple location manager that normally works, however when the Android device has been turned off and then turned back on, the android location manager returns Null even when I have it requesting updates. I am aware that getLastKnownLocation can return null, however I believe I am handling that in my code. All suggestions Appreciated.
Apparently lon = location.getLongitude(); is crashing it.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
// request location update!!
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lon = location.getLongitude();
lat = location.getLatitude();
}
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Get last known location
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Update if not null
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
//Request update as location manager can return null otherwise
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lat = location.getLatitude();
lon = location.getLongitude();
}
}
the android location manager returns Null even when I have it requesting updates
Correct. Requesting updates requests that Android start trying to find out where the device is. That will take a while. In the meantime, getLastKnownLocation() can very well return null.
getLastKnownLocation() is generally only useful if you would like to know the location, but if that data is not ready, you can move on without it. If you need the location, and getLastKnownLocation() returns null, you will to wait to use the Location until onLocationChanged() is called. Note that onLocationChanged() may never be called, as there is no requirement that the user have any location providers enabled, and there is no requirement that the device be in a position to actually get location fixes.
I saw your reply on the airplane mode but you do however have bad practices in your code.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
// request location update!!
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lon = location.getLongitude();
lat = location.getLatitude();
}
you already saw here that location in null, that means that you can't access the inner properties such as latitude and longitude. In any case, location requests are asynchronous and it takes a short amount of time for them to start.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Get last known location
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Update if not null
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
//Request update as location manager can return null otherwise
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lat = location.getLatitude();
lon = location.getLongitude();
}
}
Even here, in the "else" clouse, you can't access the location right away. that means that you can't immediately get the location (it will just hold the last value).
What you should do is implement the onLocationChanges method and hadle the location there in asynchronous way. like this:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
}
The only problem was that I had airplane mode enabled on the Android Phone. I'm a bit embarrassed now!

LocationManager throws NullPointerExpection

Please I have this code which has been working for me all this while, all of a sudden it is not working any more, it returns null pointer exception at
double lat = (double) (lastKnownLocation.getLatitude());.
I have set all required permission at the manifest file , but it seems not to work again. I think there must be a problem using the GPS provider now.
latituteField = (TextView) findViewById(R.id.TextViewLatitudeValue);
longitudeField = (TextView) findViewById(R.id.TextViewLongitudeValue);
SpeedField = (TextView) findViewById(R.id.textViewSpeedValue);
AltitudeField = (TextView) findViewById(R.id.textViewAltitudeValue);
AddressLabel=(TextView)findViewById(R.id.textViewAddress);
lbllatitude=(TextView)findViewById(R.id.lblLatDMS);
lbllongitude=(TextView)findViewById(R.id.lblLongDMS);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// GPS_PROVIDER
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if (locationProvider!= null)
{
Toast.makeText(this, locationProvider +" has been selected",Toast.LENGTH_SHORT).show();
onLocationChanged(lastKnownLocation);
}
else
{
latituteField.setText("0.00");
longitudeField.setText("0.00");
AltitudeField.setText("0.00");
SpeedField.setText("0.00");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location lastKnownLocation) {
double lat = (double) (lastKnownLocation.getLatitude());
double lng = (double) (lastKnownLocation.getLongitude());
double Alt = (double) (lastKnownLocation.getAltitude());
double Speed = (double) (lastKnownLocation.getSpeed());
latituteField.setText(String.format("%.5f",lat));
longitudeField.setText(String.format("%.5f",lng));
AltitudeField.setText(String.format("%.5f",Alt));
SpeedField.setText(String.format("%.5f",Speed));
LastKnownLocation will return null if either the location it has is too old or if the provider has never been turned on. You must take this into account. THe only way to be sure to get a valid location is to request updates and get it in onLocationChanged.
ALso, lastKnownLocation may return a value that's very wrong- something from 10 or 15 minutes ago is possible. You can use it, but don't expect accuracy.

issues to get the Latitude using network and GPS provider

Hi I have implemented a location listener in my app which uses the Network Provider to get the GPS values. It's working fine, but now I want to get GPS using network provider and GPS provider. am trying but am getting the same value.
here my code
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Where i have to use networkLoc and gpsLoc?
#Override
public void onLocationChanged(Location location) {
double lat1 = (double) (location.getLatitude());//here i get the latitude value..how to know these values are from different provider
double lng1= (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
}
It may be the case, that if the user has GPS Enabled your line
provider = locationManager.getBestProvider(criteria, false);
is returning LocationManager.GPS_PROVIDER already, so you just query getLastKnownLocation(provider) twice with the same Provider. Try this instead:
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
or if you really don't care which one to use
List<String> providers = locationManager.getProviders(false);
Location[] loc = new Location[providers.size];
int i = 0;
for (String provider: providers){
loc[i++] = locationManager.getLastKnownLocation(provider);
}
EDIT: due to refactoring of the question
//query provider from Location
public void onLocationChanged(Location loc){
String provider = loc.getProvider();
if (provider.equals(LocationManager.GPS_PROVIDER)){
//GPS Location
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)){
//Network Location
}
....
}

Showing User's Location in Android

I have a problem in getting the user's location (my location). My code is
double lat;
double lng;
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(!locationManager.isProviderEnabled(provider)){
locationManager.setTestProviderEnabled(provider, true);
}
boolean enabled = locationManager.isProviderEnabled(provider);
if(enabled){
Toast.makeText(LoginActivity.this,"provider enabled",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"provider disabled",Toast.LENGTH_LONG).show();
}
if(location!=null){
lat = location.getLatitude();
lng = location.getLongitude();
AlertDialog.Builder ab=new AlertDialog.Builder(LoginActivity.this);
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>Location" +"</font></b><br>"
+location.toString()+"<br>Latitude: "+lat
+"<br>Longitude "+lng));
ab.setPositiveButton("ok",null );
Toast.makeText(LoginActivity.this,"You are at "+location.toString(),Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"Location not found",Toast.LENGTH_LONG).show();
}
My problem is I am getting the location as null while the application message provider is enabled. I have not found any problem in this code. I have also tested it on a device, it shows the provider is enabled and the location isn't found.
I have not implemented the location listener in the class.
Is it necessary to implement location listener in my class?
You are only getting the last known location from the phone. If this is null, which it is if no last known location is available, you are not trying to receive locations in any other way.
You should implement a LocationListener an register it to receive location updates according to this guide: http://developer.android.com/guide/topics/location/obtaining-user-location.html This will cause the phone to try to get the users location and hand it over to your application in the form of a Location object.

Categories

Resources