Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8141981
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T12:41:00+00:00 2026-06-06T12:41:00+00:00

Hello StackOverflow :) I have created some code inside my onStart(); method to ensure

  • 0

Hello StackOverflow 🙂

I have created some code inside my onStart(); method to ensure that the user has GPS enabled so i can figure out in which country is he right now. If GPS is disabled, it should show an alert dialog prompting the user to enable GPS before using the app.

For some reason, it seems like that whole chunk of code isn’t working. I have disabled GPS and nothing is happening, no dialog and nothing like that. Why is this happening?

Here is my code:

    @Override
protected void onStart() {
    super.onStart();

    LocationManager locationManager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Geocoder code = new Geocoder(TipCalculatorActivity.this);
    try {
        Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
        CountryName = adr.getCountryCode();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (!gpsEnabled) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("This application requires GPS connectivity to determine your current country, and deliver you accurate tip ratings. Do you wish to turn GPS on?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        TipCalculatorActivity.this.enableLocationSettings();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        TipCalculatorActivity.this.finish();
                        System.exit(1);
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

private void enableLocationSettings() {
    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(settingsIntent);
}

Thanks a lot for any help 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T12:41:02+00:00Added an answer on June 6, 2026 at 12:41 pm

    Location loc = locationManager
    .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    Is may be returning null in your case since your mobile has no cached locations.

    So change your code to

    if (loc != null) {
        Geocoder code = new Geocoder(AbcActivity.this);
        try {
            Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
            // CountryName = adr.getCountryCode();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    If you need to query current Location.Then you need to have active Data connection or GPS turned on.
    Following Snippet will help you

    import android.app.Activity;
    import android.content.Context;
    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class ShowLocationActivity extends Activity implements LocationListener {
        private TextView latituteField;
        private TextView longitudeField;
        private LocationManager locationManager;
        private String provider;
    
    
    /** Called when the activity is first created. */
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            latituteField = (TextView) findViewById(R.id.TextView02);
            longitudeField = (TextView) findViewById(R.id.TextView04);
    
            // Get the location manager
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            // Define the criteria how to select the locatioin provider -> use
            // default
            Criteria criteria = new Criteria();
            provider = locationManager.getBestProvider(criteria, false);
            Location location = locationManager.getLastKnownLocation(provider);
    
            // Initialize the location fields
            if (location != null) {
                System.out.println("Provider " + provider + " has been selected.");
                int lat = (int) (location.getLatitude());
                int lng = (int) (location.getLongitude());
                latituteField.setText(String.valueOf(lat));
                longitudeField.setText(String.valueOf(lng));
            } else {
                latituteField.setText("Provider not available");
                longitudeField.setText("Provider not available");
            }
        }
    
        /* Request updates at startup */
        @Override
        protected void onResume() {
            super.onResume();
            locationManager.requestLocationUpdates(provider, 400, 1, this);
        }
    
        /* Remove the locationlistener updates when Activity is paused */
        @Override
        protected void onPause() {
            super.onPause();
            locationManager.removeUpdates(this);
        }
    
        @Override
        public void onLocationChanged(Location location) {
            int lat = (int) (location.getLatitude());
            int lng = (int) (location.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onProviderEnabled(String provider) {
            Toast.makeText(this, "Enabled new provider " + provider,
                    Toast.LENGTH_SHORT).show();
    
        }
    
        @Override
        public void onProviderDisabled(String provider) {
            Toast.makeText(this, "Disabled provider " + provider,
                    Toast.LENGTH_SHORT).show();
        }
    }
    

    Finally make sure you have added following permissions.

    < uses - permission android: name = "android.permission.ACCESS_FINE_LOCATION" / > 
    < uses - permission android: name = "android.permission.ACCESS_COARSE_LOCATION" / >
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hello stackoverflow community, I have some code that works on virtually every browser except
https://stackoverflow.com/a/64983/468251 - Hello, I have question about this code, how made that working with
Hello StackOverflow'ers, I have a (flex) app that, on the click of a button,
Suppose I have this code: String encoding = UTF-16; String text = [Hello StackOverflow];
Hello people of StackOverflow! I have used the searrch option, I've found some related
Hello StackOverflow community, I have run into a problem that quite frankly is baffling
Hello StackOverflow, I have an ASP.NET/C# webpage that calls functions from a managed .dll
Hello All at StackOverflow, over the last few days I have had some problems
Hello stackoverflow contributors! I have this script that gets the starting position of my
Code can be found here: http://www.myhorizon.ca/client_central/sortable_test.php Hello folks of Stackoverflow, I have a list

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.