I'm developing an Android app which achieve the position through NETWORK_PROVIDER, but I have problems on executing it on Android 7 (while it correctly works on previous versions). This is the code:
LocationManager posM;
double latitude;
double longitude;
List<Address> addresses = null;
try {
posM = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = posM.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
Geocoder geocoder;
geocoder = new Geocoder(Activity1.this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
I don't know why it crashes on Android 7... Thank you for help
Because getLastKnownLocation returns null most of the time. The system generally doesn't know your location. Use requestLocationUpdates or requestSingleUpdate to turn on the location detection and get the actual location.
Related
I've got a activity that onCreate, it calculates the distance between your location and a event that is nearby, I've used lastKnownLocation to get the current device location and put a marker of it on a google map, but I need it to write the longitude and latitude outside of it's method to be used to calculate distances.
I've used LocationManager to get the rough coordinates but these aren't accurate enough and has a distance of 50 miles for something that's not even half a mile away. I currently have it so will overwrite longitude and latitude got from LocationManager but it does not.
I've attempted to use LocationRequest too and that hasn't helped.
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(60000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult){
if(locationRequest==null){
return;
}
for(Location location : locationResult.getLocations()) {
if (location != null){
userLat=location.getLatitude();
userLng=location.getLongitude();
}
}
}
};
LocationServices.getFusedLocationProviderClient(EventLocator.this).requestLocationUpdates(locationRequest,locationCallback, null);
LocationServices.getFusedLocationProviderClient(EventLocator.this).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location!=null){
double longitude=location.getLongitude();
double latitude=location.getLatitude();
userLng=longitude;
userLat=latitude;
}
}
});
All the permissions are correct, as I said I've used getLastLocation() to place a marker.
Make sure you added location permission in manifest file
If you are using android os 6 above make sure you have location permission
Make sure you GPS service is enabled in you mobile
public Location getLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocationGPS != null) {
return lastKnownLocationGPS;
} else {
Location loc = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
System.out.println("1::"+loc);----getting null over here
System.out.println("2::"+loc.getLatitude());
return loc;
}
} else {
return null;
}
}
If still not working try to restart your phone and then try again.
You can create interface and implement it in the class where you need to calculate the distance
Usually GPS takes time to warm up. Your initial location reading could be from a cold GPS. In order to get a more accurate reading keep reading results until you get an accuracy reading that works for you.
Keep in mind GPS on a phone is not very accurate and would not be able to get accurate readings inside buildings or if not enough coverage is in your area at the time.
Last know position does not give you your current position, like it says it is the last know position which could have been more than a few minutes ago. Also it could've come from a cell tower reading instead of a GPS reading.
I'm using this code
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
lateinit var latitude : Double
lateinit var longitude : Double
override fun onCreate() {
super.onCreate()
fusedLocationProviderClient = FusedLocationProviderClient(this)
updateLocationTracking()
}
#SuppressLint("MissingPermission")
private fun updateLocationTracking() {
if(PermissionUtility.isPermissionsGranted(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
val request = LocationRequest().apply {
interval = LOCATION_UPDATE_INTERVAL
fastestInterval = FASTEST_LOCATION_INTERVAL
priority = PRIORITY_HIGH_ACCURACY
}
fusedLocationProviderClient.requestLocationUpdates(
request,
locationCallback,
Looper.getMainLooper()
)
}
}
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult?) {
super.onLocationResult(result)
result?.locations?.let { locations ->
for(location in locations) {
setLocationData(location)
}
}
}
}
private fun setLocationData(location : Location){
latitude = location.latitude
longitude = location.longitude
}
}
So I figured it out when I couldn't use my phone I use for debugging and used my personal phone for testing, went on the activity and the distances were correct.
Messed around with both debug phone settings and using GPS_PROVIDER and NETWORK_PROVIDER and when my phone used just GPS to get location, it got nothing. Other phone can, so think it's safe to say my debug phone's GPS is borked.
It's a old phone that, when I got a new one, I factory reset to use for debugging, as it helped with the backwards compatibility for older phones and smaller screens. I never thought if the actual hardware was faulty too after the reset.
So error was with the phone itself not the app. Guess it goes to show have two devices to test on.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to get the difference between 2 locations of which i have taken from the gps, Whenever i click on a button to go to my MapsActivity i get crashed with this error
Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
And When i comment the code which checks difference in distance it works just fine, i don't understand the connection between the Marker options and the DistanceTo
Here's my Code (Keep in mind that all works fine it's just the DistanceTo which doesn't work)
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
if(location != null)
// this gives address list from the maps, not important and commented
{
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
// Marker options where the issue occurs
//String result = addresses.get(0).getSubLocality()+":";
//result += addresses.get(0).getLocality()+":";
// result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
} catch (IOException e) {
e.printStackTrace();
}
//Where it checks for the locations and the distance between them
if(LocationA == null) {
LocationA = location;
}
LocationB = location;
LocationA = LocationB;
DiffernceInDistance = LocationA.distanceTo(LocationB);
}
Code where i made the Map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
The issue was that i was asking for locations and also applying a marker at the same time, so markers couldn't load to the location, to solve it I commented, It doesn't crash anymore but it didn't solve my main issue (DistanceTo not working but that's not the reason i made this post therefore i won't ask for anymore help thanks )
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));
I try to get my current location. First I created LocationListener:
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location 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
myLocation = new LatLng(latitude, longitude);
}
};
The in onCreate method I try to cal requestLocatonUpates on LocationManager:
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,500f,mLocationListener);
But I get an error:
Cannot resolve method requestLocationUpdates(java.langString, long, float,com.google.android.gms.location.LocationListener)
requestLocationUpdates is a method provided in FusedLocationAPi. You should use LocationServices.FusedLocationApi.requestLocationUpdates method.
So you have to create a googleApiClient and a location request.
You can found it here : https://developer.android.com/training/location/index.html.
I am getting a null location when setting the longitutde and lattitude. I am not sure what I am doing wrong. I debugged this code with Location Services turned on and off. When they were on, the GPS_PROVIDER if statement would be true, and when they were off it neither of the conditions would be true and it would go to the else statement. However even when it confirmed the provider was enabled, the call to getLastKnownLocation returned null. Any ideas as to why?
private void setCoordinates(Context context) {
LocationManager lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Location location = null;
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Log.e("AlarmLocation", "unable to get location");
}
This question already has an answer here:
android requestLocationUpdates failing
(1 answer)
Closed 2 years ago.
Is there a way to obtain information without displaying the map?
I want get my coordinate of my place during the work with other activity.
tnx a lot.
By Using LocationManager you can get lat and lang :
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
Using this code able to get latitude and Longitude values and make
sure before using application you got permission from manifest for accessing location
if(isGPS) {
Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
double lat=location.getLatitude();
double lng=location.getLongitude();
Toast.makeText(getApplicationContext(),lat+"and"+lng, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
display("GPS not Enabled");
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Use this if you want to get lat lon without internet
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLongitude();
longitude = location.getLatitude();