0

I am trying to get Latitude and Longitude from the device using FusedLocationApi . If the location is turned off I am asking the user to turn on the location service through a dialog. Once the location service is turned on sometime I am getting the Longitude and Latitude . But sometime its returning Location as null. Here is the code to get the Latitude and Longitude using the FusedLocationApi. Problem comes when the user has to turn on the Location Service using the dialog

private void getLatLong() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                // The next two lines tell the new client that “this” current class will handle connection stuff
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                //fourth line adds the LocationServices API endpoint from GooglePlayServices
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    protected void onPause() {
        super.onPause();
        overridePendingTransition(0, 0);
        //Disconnect from API onPause()
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //Now lets connect to the API
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (mGoogleApiClient.isConnected()) {
            Log.e("GoogleApiClient", "Connected");
            settingsRequest();
        }
    }

    private void settingsRequest() {
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1000); // 1 second, in milliseconds
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                Log.e("StatusCode", status.getStatusCode() + "");
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.e("GoogleAfterLocation", mGoogleApiClient.isConnected() + "");
                        if (mGoogleApiClient.isConnected()) {

                            // check if the device has OS Marshmellow or greater than
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
                                if (ActivityCompat.checkSelfPermission(RegistrationActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(RegistrationActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                    ActivityCompat.requestPermissions(RegistrationActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION_CODE);
                                } else {
                                    // get Location
                                    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                                    Log.e("Location", location + "");
                                    if (location == null) {
                                        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, RegistrationActivity.this);

                                        Alerter.create(RegistrationActivity.this)
                                                .setTitle(R.string.warning)
                                                .setDuration(2000)
                                                .setBackgroundColor(R.color.dot_dark_screen1)
                                                .setText("Please turn on the Location from settings and start the application")
                                                .show();

                                    } else {
                                        //If everything went fine lets get latitude and longitude
                                        currentLatitude = location.getLatitude();
                                        currentLongitude = location.getLongitude();
                                        if (currentLatitude != -0.0 && currentLongitude != -0.0) {
                                            //Get Weather Data
                                            //getWeatherData(currentLatitude, currentLongitude);
                                            Log.e("PermissionGranted", currentLatitude + " " + currentLongitude);
                                        } else {
                                            Alerter.create(RegistrationActivity.this)
                                                    .setTitle(R.string.warning)
                                                    .setText("Please Check internet connectivity")
                                                    .setDuration(1500)
                                                    .setBackgroundColor(R.color.dot_dark_screen1)
                                                    .show();
                                        }
                                        // Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
                                    }
                                }
                            } else {
                                // get Location
                                Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                                if (location == null) {
                                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, RegistrationActivity.this);

                                } else {
                                    //If everything went fine lets get latitude and longitude
                                    currentLatitude = location.getLatitude();
                                    currentLongitude = location.getLongitude();
                                    if (currentLatitude != -0.0 && currentLongitude != -0.0) {
                                        //Get Weather Data
                                        //getWeatherData(currentLatitude, currentLongitude);
                                        Log.e("Lollipop", currentLatitude + " " + currentLongitude);
                                    } else {
                                        Alerter.create(RegistrationActivity.this)
                                                .setTitle(R.string.warning)
                                                .setText("Please Check internet connectivity")
                                                .setDuration(1500)
                                                .setBackgroundColor(R.color.dot_dark_screen1)
                                                .show();

                                    }
                                    // Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
                                }
                            }

                        }
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(RegistrationActivity.this, REQUEST_RESOLVE_ERROR);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        });
    }

    // This method is called only on devices having installed Android version >= M (Marshmellow)
    // This method is just to show the user options for allow or deny location services at runtime
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 3310: {

                if (grantResults.length > 0) {

                    for (int i = 0, len = permissions.length; i < len; i++) {

                        if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                            // Show the user a dialog why you need location
                        } else if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            // get Location
                            getLatLong();
                        } else {
                            finish();
                        }
                    }
                }
                return;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("RequestCode", requestCode + "");
        if (requestCode == REQUEST_RESOLVE_ERROR) {
            mResolvingError = false;
            switch (resultCode) {
                case Activity.RESULT_OK:
                    Log.e("LocationDialog", "Turned On");
                    // get location method
                    if (ActivityCompat.checkSelfPermission(RegistrationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(RegistrationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                    if (location == null) {
                        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, RegistrationActivity.this);

                    } else {
                        //If everything went fine lets get latitude and longitude
                        currentLatitude = location.getLatitude();
                        currentLongitude = location.getLongitude();
                        if (currentLatitude != -0.0 && currentLongitude != -0.0) {
                            //Get Weather Data
                            //getWeatherData(currentLatitude, currentLongitude);
                        } else {

                            Alerter.create(RegistrationActivity.this)
                                    .setTitle(R.string.warning)
                                    .setText("Please Check internet connectivity")
                                    .setDuration(1500)
                                    .setBackgroundColor(R.color.dot_dark_screen1)
                                    .show();

                        }

                        //Toast.makeText(getActivity(), currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
                    }
                    break;
                case Activity.RESULT_CANCELED:
                    finish();
                    break;
            }
        }
    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
        if (connectionResult.hasResolution()) {
            try {
                mResolvingError = true;
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(RegistrationActivity.this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                mGoogleApiClient.connect();
            }
        } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
            showErrorDialog(connectionResult.getErrorCode());
            mResolvingError = true;
            Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    /* Creates a dialog for an error message */
    private void showErrorDialog(int errorCode) {
        // Create a fragment for the error dialog
        ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
        // Pass the error that should be displayed
        Bundle args = new Bundle();
        args.putInt(DIALOG_ERROR, errorCode);
        dialogFragment.setArguments(args);
        dialogFragment.show(getSupportFragmentManager(), "errordialog");
    }

    /* Called from ErrorDialogFragment when the dialog is dismissed. */
    public static void onDialogDismissed() {
        mResolvingError = false;
    }


    /* A fragment to display an error dialog */
    public static class ErrorDialogFragment extends DialogFragment {
        public ErrorDialogFragment() {
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Get the error code and retrieve the appropriate dialog
            int errorCode = this.getArguments().getInt(DIALOG_ERROR);
            return GoogleApiAvailability.getInstance().getErrorDialog(
                    this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            onDialogDismissed();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
    }

This line is returning null after the location is turned on:

Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
sagar suri
  • 4,351
  • 12
  • 59
  • 122

0 Answers0