DistanceTo Crashes application when running [duplicate] - java

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"));

Related

Getting longitude and latitude from lastKnownLocation()?

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.

Google Maps NullPointerException while retrieving Latitude and Longitude

am trying to create a Google Maps activity that gets the users current location and places a pin on the users' current location. I have tried the code with static latitude and longitude values and the map worked as it should. When I tried to get the LatLong values programmatically, the system threw a NullPointerException at line 127 containing the code double longitude = location.getLongitude();.
What am I doing wrong and how can I rectify it? Thanks in advance for your assistance.
Activity Code
#Override
public void onMapReady(GoogleMap googleMap) {
try {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
}
} catch (Exception e){
e.printStackTrace();
}
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
gmap = googleMap;
gmap.setMinZoomPreference(12);
gmap.setIndoorEnabled(true);
UiSettings uiSettings = gmap.getUiSettings();
uiSettings.setIndoorLevelPickerEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setMapToolbarEnabled(true);
uiSettings.setCompassEnabled(true);
uiSettings.setZoomControlsEnabled(true);
LatLng ny = new LatLng(latitude, longitude);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
}
Logcat
Process: ke.co.mytech.mytech, PID: 8425
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
at ke.co.mytech.mytech.HomeFragment.onMapReady(HomeFragment.java:127)
at com.google.android.gms.maps.zzac.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source)
at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:392)
at fg.b(:com.google.android.gms.dynamite_mapsdynamite#13280046#13.2.80 (040306-211705629):19)
at com.google.android.gms.maps.internal.bg.a(:com.google.android.gms.dynamite_mapsdynamite#13280046#13.2.80 (040306-211705629):5)
at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_mapsdynamite#13280046#13.2.80 (040306-211705629):5)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
A few things that might help.
One, try using the FusedLocationProviderClient to get the location.
FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.i(TAG, "Latitude: " + latitude + " | Longitude: " + longitude);
} else {
Log.e(TAG, "Unable to retrieve location");
}
}
});
Second, I had this issue when I was testing on the emulator and it always raised the same exception as you are mentioning. What I did to fix it was to go into the Google Maps application on my emulator and let it pinpoint my location by clicking on the circle target button. I am not sure as to why it worked (I think it was because it saved my location which it was unable to do before).
Got the answer to what I was doing wrong in this question

Android APP crash on getLastKnownLocation()

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.

search location name in google map

I tried to search location name in google map activity.here in onsearch method address.getLatitude() and address.getLongitude are not work.its show red text.anyone please solve my error. below my code
public void onSearch(View view)
{
EditText location_tf = (EditText)findViewById(R.id.TFaddress);
String location = location_tf.getText().toString();
List<Address> addressList = null;
if(location != null || !location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location , 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude() , address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(0,0);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
It seems that, you have either imported the wrong Address class or not imported at all. The class which you are looking for can be imported using following line:
import android.location.Address;
The above class contains getLatitude() and getLongitude() methods. Another package which also contains Address class, which I guess, by mistake you imported is following:
com.google.android.gms.identity.intents

get latitude and longitude in Android without show the map [duplicate]

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();

Categories