本文介绍了FusedLocationProviderClient:空对象引用上的Location.getLatitude()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取地址城市名称,然后将其放在字符串中,用户应首先打开GPS.我已经尝试了很多代码,但是什么也没发生.直到找到这个,然后我从穿上跟随JavaVersion来获取经度和纬度.

I want to get address City Name and then put it in String, and user should turn on GPS first. I've tried many code but nothing happended. Until I found this, and I following JavaVersion from this answear to get latitude and longitude.

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

但是随后我在一个空对象引用上得到了Location.getLatitude():

but then I got this Location.getLatitude() on a null object reference :

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
}

这篇关于FusedLocationProviderClient:空对象引用上的Location.getLatitude()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 01:53