简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM