Location is null even if GPS is turned on - android

I am working on google maps. I want to get the user location and show him on the map. I wrote a Locationlistener to get the user location.
public Location getUserLocation(){
try {
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
return null;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,DISTANCE_CALC,TIME_UPDATE, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,DISTANCE_CALC,TIME_UPDATE, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
The getUserLocation() is one of the functions in the LocationListener that will return the user location with either the GPS or the network. I am calling this function from a fragment like this.
if (Build.VERSION.SDK_INT >= 23){
if (checkPermission()) {
location = locHandler.getUserLocation();
if(location!=null)
showTheMaps(location);
else
AlertBuilder(title,body);
}else {
requestPermission();
}
}else {
//The build is less than marshmellow so no need for permission
location = locHandler.getUserLocation();
try {
// double d = location.getLatitude();
showTheMaps(location);
}catch (NullPointerException e){
AlertBuilder(title, body);
}
}
public void showTheMaps(Location location){
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()), DataModel.zoomlevel);
googleMap.animateCamera(cameraUpdate);
}
The AlertBuilder function will show an alert box with a button which upon click closes the app.
As you can see from the screenshot the GPS is enabled yet the location returned to me is null and the app closes after showing the alert dialog.
What could be the problem? why is the location returning null even after turning on the GPS?

Use
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
Source: https://developer.android.com/training/location/retrieve-current.html
Another (deprecated) way is to set a OnMyLocationChangeListener to your map to get the location
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
// do something with location
}
});
More info: how to get current location in google map android

Related

Get user current lat lng after GPS enabled - Android

I have followed this tutorial http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ for showing popup if GPS in not enabled and getting users current location.
And here is the broadcast receiver which listens to the GPS enabled disabled condition
private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
gps = new GPSTracker(getActivity());
if(gps.canGetLocation()){
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
Toast.makeText(getActivity(), "GPS Switch", Toast.LENGTH_SHORT).show();
if(gps.getLatitude() != 0 && gps.getLongitude() != 0 ){
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(gps.getLatitude(),gps.getLongitude())) // Sets the center of the map to selected place
.zoom(15) // Sets the zoom
.build(); //
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Toast.makeText(getActivity(), "GPS Switch Lat: "+gps.getLatitude()+" Long: "+gps.getLongitude(), Toast.LENGTH_SHORT).show();
}
} else {
if(!gps.isSettingDialogShown())
gps.showSettingsAlert();
}
}
}
};
When I enable the GPS via settings dialog or from drop down menu. GPSTracker class gets the location service and checks for the user's current location in this code fragment
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);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
return location;
}
Problem:
Firstly I don't know why broadcast receiver, receives the action two times and secondly when in normal mode lat lng value in receiver remains zero but in debugging sometimes it returns the value of users current location.
Can you please help what I am doing wrong?
If you don't need to work with Gps and Network Locations separately. I recommend to use FusedLocationProvider. BroadcastReceiver is probably working twice because it works for both gps and network location services

Unable to locate my device

There's a problem with Location... I'm using method to get latitude and longtitude. But my Location variable is null. So my coordinates are 0,0.
Can anybody help me,pls?
Here's code:
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, R.string.no_service, Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
} catch (SecurityException e) {
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
loc is null anyway. When I'm compiling app, GPS and wifi are enabled on my phone.
Given that you're swallowing the SecurityExceptions, I'm guessing your app did not request permission to ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION, needed for Network and GPS location, respectively.
I generally recommend against silently swallowing exceptions. These particular SecurityExceptions, you should have never needed to add a catch statement for them (that was your clue that something was wrong), b/c you should've called checkSelfPermission() before attempting to access the resource.

Locationhandler does not return Location with Samsung Galaxy

I've created a location tracker application who send the location of a mobile device to a database.
When I test the location with my old samsung device (without a SIM) the application works. He sends the locationmanager and sends it to the db.
But when I test the application with my newer device. A samsung Galaxy. The application does not work. It can't calculate the location because he says 'GPSisenabled' is false and 'NetworkedEnabled' is also false..
Here's my code to determine the location. Maybe someone has a answer to this strange thing, thanks
public Location getLocation() {
try {
ConfigurationManager();
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
return null;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location = null;
Log.d("Network", "Network - GET LOCATION ");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
location = null;
if (location == null) {
Log.d("GPS Enabled", "GPS Enabled - GET LOCATION");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
You should use FusedLocationProviderApi for getting the current location as per android documentation. Read more here : Getting the Last Known Location

Android: how to check the location is current location or last known location

In my app I getting location from network and if network is not not available my code returns the last location, In both the cases I want to know whether the location is current location or it is the last known location. can somebody please show me how to know this.Thanks in advance
public Location getLocation() {
try {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
else{ }
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
You need to achieve this using SharedPrefences
Store the current location(the latitude and longitude upto approx 5 decimal places) in shared preferences.Compare the new location with that in the shared preferences.If they are same,then the new location is your last known location,if not the new location is the new one,save it again in your shared preference.

some devices do not return current latitude longitude

I am trying to get the address of the user, for that i need the current latitude and longitude of the user. I am using following code for the same
public LatLng getCurrentLocation(Context context) {
try {
LocationManager locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String locProvider = locMgr.getBestProvider(criteria, false);
Location location = locMgr.getLastKnownLocation(locProvider);
// getting GPS status
boolean isGPSEnabled = locMgr
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNWEnabled = locMgr
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNWEnabled) {
Log.v(TAG, "Network and GPS are unavailable");
// no network provider is enabled
return null;
} else {
// First get location from Network Provider
if (isNWEnabled) {
Log.v(TAG, "Network is enabled for getting the location");
if (locMgr != null) {
Log.v(TAG,
"Location manager is not null so fetch the location from network");
location = null;
location = locMgr
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
if (locMgr != null)
location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
return new LatLng(location.getLatitude(), location.getLongitude());
} catch (NullPointerException ne) {
Log.e(TAG, "Current Lat Lng is Null");
return new LatLng(0, 0);
} catch (Exception e) {
e.printStackTrace();
return new LatLng(0, 0);
}
}
In my Moto e with android 4.4 it is working very good but in some of the devices it does not return the lat lng and i get 0,0 which is returned in the exception.
What i need to change to get it correct in all devices.

Categories

Resources