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
Related
hello i wanna create a attandace online using getlocation
everything works fine until i close the app and forget to turn on the GPS service
everytime i open activity to get geoLocation code is always failed ,
what i ask is how can in get current location using google maps api so everytime i open the apps is works to get location geocodes
Please Help Im struggle to solve this i need this app for my final project
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.sistemabsensi.online.Absensi.onConnected(Absensi.java:415)
at com.google.android.gms.common.internal.GmsClientEventManager.onConnectionSuccess(Unknown Source:33)
at com.google.android.gms.common.api.internal.zaaw.zab(Unknown Source:292)
at com.google.android.gms.common.api.internal.zaak.zaaq(Unknown Source:125)
at com.google.android.gms.common.api.internal.zaak.onConnected(Unknown Source:105)
at com.google.android.gms.common.api.internal.zabe.onConnected(Unknown Source:101)
at com.google.android.gms.common.api.internal.zaq.onConnected(Unknown Source:6)
at com.google.android.gms.common.internal.zaf.onConnected(Unknown Source:2)
at com.google.android.gms.common.internal.BaseGmsClient$zzf.zzm(Unknown Source:24)
at com.google.android.gms.common.internal.BaseGmsClient$zza.zza(Unknown Source:12)
at com.google.android.gms.common.internal.BaseGmsClient$zzc.zzo(Unknown Source:11)
at com.google.android.gms.common.internal.BaseGmsClient$zzb.handleMessage(Unknown Source:49)
at android.os.Handler.dispatchMessage(Handler.java:107)
at com.google.android.gms.internal.common.zze.dispatchMessage(Unknown Source:8)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
I/Process: Sending signal. PID: 27425 SIG: 9
Heres My code :
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
#SuppressLint("MissingPermission") Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latit = location.getLatitude();
double longit = location.getLongitude();
LatLng kantor = new LatLng(-8.4603894,118.7560158);
LatLng User = new LatLng(latit,longit);
distance=SphericalUtil.computeDistanceBetween(User,kantor);
TextView jarak = findViewById(R.id.jarak);
jarak.setText("Jarak Dari Kantor :" + Math.round(distance) + " Meter");
Log.d(TAG,"Latitude" + String.valueOf(latit) +"Longitude" + String.valueOf(longit));
On Location Change works fine but this not i expected
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latLng.latitude, latLng.longitude)).zoom(16).build();
latitude = location.getLatitude();
longitude = location.getLongitude();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
#SuppressLint("MissingPermission") Location location1 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latit = location.getLatitude();
double longit = location.getLongitude();
float[] results = new float[1];
Location.distanceBetween(latit,longit,-8.4604926,118.7560354,results);
float distance = results[0];
int meter = (int) (distance/10000);
TextView jarak = findViewById(R.id.jarak);
Android 10 introduced new permission called background location:
https://developer.android.com/training/location/permissions#background
For Android 10 devices or above, to get location while app is in background:
You need to declare Background Location permission in manifest.
Users must grant this permission in runtime.
(Update) Location services must be enabled on device.
(Update) Sample code:
Declare fine and background permission in AndroidManifest.xml (in manifest tag):
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
This is how you request these permissions from your Activity class (no permissions before Android 6):
// Android 10+
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION}, REQUEST_CODE);
// Android 6-9
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
This is how you check the result from your activity for Android 10+ devices (2 levels of permissions):
// Utility function
#RequiresApi(api = Build.VERSION_CODES.M)
public boolean isPermissionGranted(String permission) {
return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
// Only fine location granted - no location if app is closed
isPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION) && !isPermissionGranted(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
// Fine & background location granted - location should (almost) always work:
isPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION) && isPermissionGranted(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
For Android 6-9 devices you can just check for Manifest.permission.ACCESS_FINE_LOCATION
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();