0

I am trying to create an app that will get the current location of the phone and display it as a marker on the map. I am using devices with different types of android versions. It worked fine in Lollipop and displayed my current location but it's not working on the other versions, it only displays the map. It doesn't provide me an error message so I'm not really sure what is happening.

This is the code that I used to get the current location:

public void getLocation() {
    try {
        _locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        isGPSEnabled = _locationManager.isProviderEnabled(_locationManager.GPS_PROVIDER);
        isNetworkEnabled = _locationManager.isProviderEnabled(_locationManager.NETWORK_PROVIDER);

        if (_locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        if (_locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
            _locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

        // Ask for update
        Location mobileLocation = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (mobileLocation != null) {
            onLocationChanged(mobileLocation);
        }
        Location netLocation = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (netLocation != null) {
            onLocationChanged(netLocation);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onLocationChanged(Location userLocation) {

    if (userLocation == null) {
        Log.e(TAG, "NO Internet");
        return;
    }

    _longitude = userLocation.getLongitude();

    _latitude = userLocation.getLatitude();

    if (marker != null) {
        marker.remove();
    }

    marker = mMap.addMarker(new MarkerOptions().position(new LatLng(_latitude, _longitude)).title("I'm Here"));

    String cityName = null;
    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
    List<Address> addresses;

    try {
        addresses = gcd.getFromLocation(userLocation.getLatitude(), userLocation.getLongitude(), 1);
        if (addresses.size() > 0)
            cityName = addresses.get(0).getLocality();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String fullLocation = "Longitude : " + userLocation.getLongitude() + "\nLatitude : " + userLocation.getLatitude() + "\n\nMy Current City is: " + cityName;
    Log.e(TAG, "location : " + fullLocation);

}

Thank you!

2 Answers2

0

try this answer. Sometimes getLastKnownLocation() returns null. So you have to add location update request also..

Vinayak B
  • 4,430
  • 4
  • 28
  • 58
0

For Marshmallow and above you have to explicitly ask user for permission. You can use this code to achieve it

private void RequestAllPermissions() {

        String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.RECEIVE_SMS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_CONTACTS};

        if (!hasPermissions(this, PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUESTCODE_PERMISSION_ALL);
        } else

    }

public static boolean hasPermissions(Context context, String... permissions) {

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;

    }


@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    switch (requestCode) {
        case REQUESTCODE_PERMISSION_ALL: {

            boolean allpermissiongranted = true;
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        allpermissiongranted = false;
                        break;
                    }
                }
            } else
                allpermissiongranted = false;

            if (allpermissiongranted) {
                //do task

            } else {

                new SweetAlertDialog(mContext, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("Permission Not Granted")
                        .setContentText("Kindly grant all requested permission to proceed.")
                        .setConfirmText("Request")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.dismissWithAnimation();
                                RequestAllPermissions();
                            }
                        })
                        .setCancelText("Exit")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                                finish();
                            }
                        })
                        .show();
            }

        }
Nivil Boban
  • 286
  • 1
  • 13