1

I'm working with the map to my app and so I have here a weird error message that it says java.lang.SecurityException: "GPS" location provider requires ACCESS_FINE_LOCATION permission. every time I launch the app and crashes due to this error, though I already have a permission checker.

Here is my code:

public class FragmentHome extends Fragment implements OnMapReadyCallback {

    /*
        Set up's
     */

    private static final String TAG = "FragmentHome";

    /*
        Pallete
     */


    private MapView mapView;
    private GoogleMap gMap;

    private static final String MAP_VIEW_BUNDLE_KEY = "SOME_KEY";

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);

        mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);

        return view_fragmentInflate;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        getUserLocation();
    }

    private void getUserLocation() {
        LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.i(TAG, "onLocationChanged: " + location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                requestPermissions(new String[] {
                        Manifest.permission.ACCESS_FINE_LOCATION
                }, 1);
            }
        }

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                3000, 0, locationListener);
    }
}

I really do not know where I went wrong from this line of code, to keep my app crashing and give me that error.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
User Unknown
  • 1,079
  • 1
  • 7
  • 17
  • You are trying to getLocation, when location permission is not granted. After `onMayReady()`, check for location permission granted then `getUserLocation()` – Rohit Nov 05 '19 at 07:38
  • As given in your comment (auto-generated), consider overriding the method `onRequestPermissionsResult`, then call the method `requestLocationUpdates` inside that method. Or my library may help you: https://github.com/nabinbhandari/Android-Permissions – Nabin Bhandari Nov 05 '19 at 07:39
  • @Rohit so what is the better way to do it sir? – User Unknown Nov 05 '19 at 07:39
  • 1
    I have edited my comment, it may help you :) Also never post your keys publicly – Rohit Nov 05 '19 at 07:40
  • I already found out the problem, I forgot to provide an `else` statement. – User Unknown Nov 05 '19 at 07:46
  • //used this link https://stackoverflow.com/questions/32083913/android-gps-requires-access-fine-location-error-even-though-my-manifest-file – Jitu Batiya Nov 05 '19 at 08:12
  • //try this link https://stackoverflow.com/questions/32083913/android-gps-requires-access-fine-location-error-even-though-my-manifest-file – Jitu Batiya Nov 05 '19 at 08:14

2 Answers2

0

Update your code with bellow code may solve your problem

public class FragmentHome extends Fragment implements OnMapReadyCallback {

    /*
        Set up's
     */

        private static final String TAG = "FragmentHome";

    /*
        Pallete
     */


        private MapView mapView;
        private GoogleMap gMap;

        private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";

        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);

            mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
            mapView.onCreate(savedInstanceState);
            mapView.getMapAsync(this);

            return view_fragmentInflate;
        }

        boolean isMapReady;
        @Override
        public void onMapReady(GoogleMap googleMap) {
            isMapReady=true;
            getUserLocation();
        }

        private void getUserLocation() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                        ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    Activity#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for Activity#requestPermissions for more details.
                    requestPermissions(new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION
                    }, 1);
                    return;
                }
            }

            LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
            LocationListener locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Log.i(TAG, "onLocationChanged: " + location);
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            };


            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                    3000, 0, locationListener);

        }
    }

Now override onRequestPermissionsResult() and check if result is granted and isMapReady flag true then call getUserLocation().

Dhaval Solanki
  • 4,589
  • 1
  • 23
  • 39
0

So the solution for this and base on the comments i forgot to put the else statement that if the permission is granted then execute the listener else request a permission.

Updated:

public class FragmentHome extends Fragment implements OnMapReadyCallback {

    /*
        Set up's
     */

    private static final String TAG = "FragmentHome";

    /*
        Pallete
     */


    private MapView mapView;
    private GoogleMap gMap;

    private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);

        mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);

        return view_fragmentInflate;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        checkGPSPermission();
        getUserLocation();
    }

    private void checkGPSPermission() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // show why is important
                }

                requestPermissions(new String[] {
                        Manifest.permission.ACCESS_FINE_LOCATION
                }, 1);
            } else {
                // granted
            }
        } else {
            // granted
        }
    }

    private void getUserLocation() {
        LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.i(TAG, "onLocationChanged: " + location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                requestPermissions(new String[] {
                        Manifest.permission.ACCESS_FINE_LOCATION
                }, 1);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        3000, 0, locationListener);
            }
        } else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                    3000, 0, locationListener);
        }
    }
}
User Unknown
  • 1,079
  • 1
  • 7
  • 17
  • It won't work on the first time the permission is requested at run-time. (Try it by manually disabling the permission from app's settings, or simply clearing app's data.) You will need to override the method `onRequestPermissionsResult` in order to handle such situation. – Nabin Bhandari Nov 05 '19 at 07:45
  • yeah, you got the point and already override it . but the problem is how i can put the method on the `mapcallback`? – User Unknown Nov 05 '19 at 07:51
  • Read this article: https://developer.android.com/training/permissions/requesting or use this library: https://github.com/nabinbhandari/Android-Permissions – Nabin Bhandari Nov 05 '19 at 08:00