Missing permissions required by FusedLocationProviderClient.getLastLocation: android.permission.ACCESS_COARSE_LOCATION

mFusedLocationProviderClient.getLastLocation().addOnCompleteListener and mMap.setMyLocationEnabled(true) the both line give me error which I mention in title .I dont know what is the problem ..I watch many video .but cant find the solution for this warning or say error because some times its work or some time app will crash

ShoOwnerMaps

package com.example.saloononlinewaitingsolution;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.maps.android.clustering.ClusterManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ShoOwnerMaps extends AppCompatActivity implements OnMapReadyCallback {


    public static GeoPoint gp;
    private static final String TAG = "ShoOwnerMaps";
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private Boolean mLocationPermissionGranted = false;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    private static final float DEFAULT_ZOOM = 15f;
    private GoogleMap mMap;
    private ImageView mSearchLocation;
    private FirebaseFirestore mdb;
    //CollectionReference location;
    private GeoPoint cGeoPoint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sho_owner_maps);

        mSearchLocation = (ImageView) findViewById(R.id.ic_searchLocation);
        mdb = FirebaseFirestore.getInstance();
        // location = mdb.collection("Saloons Shop Location");
        //mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
      mFusedLocationProviderClient = new FusedLocationProviderClient(this);
        getLocationPermission();



    }

    private void getLocationPermission() {
        Log.d(TAG, "getLocationPermission: getting location permission ");
        String[] permission = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};

        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
                initializeMap();
            } else {
                ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUEST_CODE);
            }
        } else {
            ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUEST_CODE);
        }

    }

 /*   @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: called ");
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission Failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission Granted");
                    mLocationPermissionGranted = true;
                    initializeMap();

                }
            }
        }
    }*/


    private void initializeMap() {
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(ShoOwnerMaps.this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();

        Log.d(TAG, "initMap : initializing map");
        mMap = googleMap;

        if (mLocationPermissionGranted) {
            // getDeviceLocation();
            lastKnownLocation();

            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED )
            {
                ActivityCompat.requestPermissions(this,new String[]
                                {Manifest.permission.ACCESS_FINE_LOCATION},
                        LOCATION_PERMISSION_REQUEST_CODE);
                mMap.setMyLocationEnabled(true);

               return;
            }
;

            mMap.getUiSettings().setMyLocationButtonEnabled(false);
            mMap.getUiSettings().setCompassEnabled(true);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setTiltGesturesEnabled(true);
            mMap.getUiSettings().setRotateGesturesEnabled(true);
            mMap.setTrafficEnabled(true);


        }
    }



    private void lastKnownLocation() {
        Log.d(TAG, "lastKnownLocation: called");

        if (ContextCompat.checkSelfPermission(this,
             Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED )
        {

            ActivityCompat.requestPermissions(this,new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);

        }

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

                if (task.isSuccessful()) {


                    Location currentLocation = task.getResult();
                    assert currentLocation != null;
                    final GeoPoint currentGeoPoint = new GeoPoint(currentLocation.getLatitude(), currentLocation.getLongitude());
                    moveCamera(new LatLng(currentGeoPoint.getLatitude(), currentGeoPoint.getLongitude()), DEFAULT_ZOOM,
                            "My Location");
                    cGeoPoint = currentGeoPoint;

                    mSearchLocation.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            gp = cGeoPoint;
                            Intent intent = new Intent(ShoOwnerMaps.this, ShopTimeDaySchedule.class);
                            startActivity(intent);
                            finish();
                        }
                    });

                }
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: called ");
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: permission Failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission Granted");
                    mLocationPermissionGranted = true;
                    initializeMap();

                }
            }
        }
    }


    private void moveCamera(LatLng latLng, float zoom, String title) {
        Log.d(TAG, "moveCamera: moving the camera to Lat " + latLng.latitude + ", lng :" + latLng.longitude);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title(title);
        mMap.addMarker(options);

    }
}

build.gradle

enter image description here

warning when I hover

enter image description here

Manifest enter image description here


Solution 1:

Check if ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION permission is granted before calling mFusedLocationProviderClient.getLastLocation() as shown below:

if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
    FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
        COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener < Location > () {
        //override methods
    });
} else {
    ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
  ActivityCompat.requestPermissions(this, permission, 
LOCATION_PERMISSION_REQUEST_CODE);
}