简体   繁体   English

FusedLocationProviderClient:null object 参考上的 Location.getLatitude()

[英]FusedLocationProviderClient : Location.getLatitude() on a null object reference

I want to get address City Name and then put it in String, and user should turn on GPS first.我想得到地址 City Name 然后把它放在 String 中,用户应该先打开 GPS。 I've tried many code but nothing happended.我尝试了很多代码,但没有发生任何事情。 Until I found this, and I following JavaVersion from this answear to get latitude and longitude.直到我发现这个,我从这个答案中遵循JavaVersion来获取纬度和经度。

private final String TAG = "MainActivity";
private FusedLocationProviderClient fusedLocationClient;
private final CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
....

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ....
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        ....
        buttonGetLocation.setOnClickListener(view -> {
           requestCurrentLocation()
        }
        ....
    }
private void requestCurrentLocation() {
        Log.d(TAG, "requestCurrentLocation()");
        // Request permission
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {

            // Main code
            Task<Location> currentLocationTask = fusedLocationClient.getCurrentLocation(
                    PRIORITY_HIGH_ACCURACY,
                    cancellationTokenSource.getToken()
            );

            currentLocationTask.addOnCompleteListener((new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {

                    String result = "";

                    if (task.isSuccessful()) {
                        // Task completed successfully
                        Location location = task.getResult();
                        result = "Location (success): " +
                                location.getLatitude() +
                                ", " +
                                location.getLongitude();

                        getAddress(location.getLatitude(), location.getLongitude()); // Get Address

                    } else {
                        // Task failed with an exception
                        Exception exception = task.getException();
                        result = "Exception thrown: " + exception;
                    }

                    Log.d(TAG, "getCurrentLocation() result: " + result);
                }
            }));
        } else {
            // TODO: Request fine location permission
            Log.d(TAG, "Request fine location permission.");
        }
    }
private void getAddress(double LATITUDE, double LONGITUDE) {

        //Set Address
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addresses != null && addresses.size() > 0) {

            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String country = addresses.get(0).getCountryName();
            String postalCode = addresses.get(0).getPostalCode();
            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

            Log.d(TAG, "getAddress:  address" + address);
            Log.d(TAG, "getAddress:  city" + city);
            Log.d(TAG, "getAddress:  state" + state);
            Log.d(TAG, "getAddress:  postalCode" + postalCode);
            Log.d(TAG, "getAddress:  knownName" + knownName);

        } else {
            Log.d(TAG, "Fail get Location!");
        }
    }

but then I got this Location.getLatitude() on a null object reference:但后来我在 null object 参考上得到了这个 Location.getLatitude() :

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at com.yayco.rebahan.MainActivity$5.onComplete(MainActivity.java:453)
        at com.google.android.gms.tasks.zzj.run(com.google.android.gms:play-services-tasks@@17.2.0:4)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6810)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

What i miss?我想念什么? Thanks for help.感谢帮助。

you can try this code, it works for me:你可以试试这个代码,它对我有用:

private LocationRequest mLocationRequest;
mLocationRequest = LocationRequest.create();

private void requestCurrentLocation() {
    Log.d(TAG, "requestCurrentLocation()");
    // Request permission
    if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION) ==
            PackageManager.PERMISSION_GRANTED) {

        // Main code
        fusedLocationClient.getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // GPS location can be null if GPS is switched off
                    if (location != null) {
                       getLocation(location);
                        
                        
                    } else {
                        if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION)
                                != PackageManager.PERMISSION_GRANTED) {
                            PermissionUtils.requestPermission((AppCompatActivity) mContext,
                                    LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, false);

                        }
                        fusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "Error trying to get last GPS location");
                    e.printStackTrace();

                }
            });
        
    } else {
        // TODO: Request fine location permission
        Log.d(TAG, "Request fine location permission.");
    }
}

private final LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult);
        if (locationResult.getLastLocation() == null) {
            //Log.e(TAG, "onLocationResult:  null");
            return;
        }
        getLocation(locationResult.getLastLocation());
    }
};

private void getLocation(Location location){
    //you will get location here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 空对象引用上的Location.getLatitude() - Location.getLatitude() on a null object reference 尽管使用了请求位置更新,仍将Location.getLatitude()显示为空对象? - Shows Location.getLatitude() a null object despite use of Request location updates? 空对象引用上的double android.location.Location.getLatitude()&#39; - double android.location.Location.getLatitude()' on a null object reference 空对象引用ParseGeoPoints上的&#39;double android.location.Location.getLatitude()&#39; - 'double android.location.Location.getLatitude()' on a null object reference ParseGeoPoints Location.getLatitude等不断变化 - Location.getLatitude etc. keeps changing Android Google Maps-NullPointerException-Location.getLatitude() - Android Google Maps - NullPointerException - Location.getLatitude() 我需要一个蓝点位置,没有位置。getLatitude/ Longtitude - I need a blue dot location, no location.getLatitude/Longtitude 尝试在空对象引用上调用虚拟方法&#39;double android.location.Location.getLatitude()&#39; - Attempt invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference 空对象引用上的虚拟方法&#39;double android.location.Location.getLatitude()&#39; - virtual method 'double android.location.Location.getLatitude()' on a null object reference 在空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”时出错 - Error invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM