Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Suleyman Orazgulyyev
PLUS
Suleyman Orazgulyyev
Courses Plus Student 5,798 Points

Fine Location Request Permission

Hey everyone!

I am currently trying to implement Google Location Services for my App. I have requested permission dynamically for the FINE LOCATION. I'm also requesting location updates in order to avoid getting null. My app crashed saying that I need a permission to request location updates. I did that. Now my app crashes saying that myLocation variable is equal to null: My onConnect:

@Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.i(TAG, "Location services connected");
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSON_CODE);
            }else{
                requestLocation();
            }
        }else{
            requestLocation();
        }

        if (myLocation == null) {
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED){
                    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSON_CODE);
                }else{
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                }
            }else{
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        }
        else {
            handleNewLocation(myLocation);
        };

and here are the functions where I request Location:

private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());
        myLocation = location;
        mLatitude.setText("Your latitude is " + myLocation.getLatitude());
    }
private void requestLocation(){
        myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        mLatitude.setText(myLocation.toString());
    }

I had the same problem in another app and I ended up using LocationManager. Could please someone tell me why the myLocation variable is null?