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)