-2

I want to detect my location, I am using ACCESS_FINE_LOCATION permission but when I run app, it crashes and on the screen occurs error message:

"AppName" has stopped working

Following is my code, I am using to implement the above said:

public class MainActivity extends AppCompatActivity {
    LocationManager locationManager;
    Location location;

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

       locationManager = (LocationManager) 
                       getSystemService(Context.LOCATION_SERVICE);
       if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
           return;
       }
       location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
       Log.v("My Coordinates are: ", location.getLatitude() + " " + location.getLongitude());
    }
}

What am I doing wrong here?

Please Help.

Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
Mathew
  • 11
  • 5
  • check this [android-gps-location-manager](https://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/) – AskNilesh Aug 30 '17 at 06:45
  • If you are using Android 6+, then this could be caused because of runtime permissions. You can read the accepted answer at https://stackoverflow.com/questions/40142331/how-to-request-location-permission-on-android-6. Also, it would be easier if you could provide your stack trace. – BajajG Aug 30 '17 at 06:55
  • There will be stacktrace in logcat which will tell you more about the problem. Check https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this/23353174#23353174 – Josef Adamcik Aug 30 '17 at 08:05
  • I get NullpointerException. What does it mean? I checked my app on my friend's device and it works. – Mathew Aug 30 '17 at 08:28

1 Answers1

0

put your permission in the manifest so you don't have to that code you did again in other activities

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

instanciate the location manager:

LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

get coordinates if the gps is enabled:

LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

this is a sample of full implementation:

private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        editLocation.setText("");
        pb.setVisibility(View.INVISIBLE);
        Toast.makeText(
                getBaseContext(),
                "Location changed: Lat: " + loc.getLatitude() + " Lng: "
                    + loc.getLongitude(), Toast.LENGTH_SHORT).show();
        String longitude = "Longitude: " + loc.getLongitude();
        Log.v(TAG, longitude);
        String latitude = "Latitude: " + loc.getLatitude();
        Log.v(TAG, latitude);

        /*------- To get city name from coordinates -------- */
        String cityName = null;
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(),
                    loc.getLongitude(), 1);
            if (addresses.size() > 0) {
                System.out.println(addresses.get(0).getLocality());
                cityName = addresses.get(0).getLocality();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
            + cityName;
        editLocation.setText(s);
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}
}
Orvenito
  • 437
  • 2
  • 14
  • Thank you for your help but locationlistener updates coordinates when you're moving and I want to get my location everytime even if I am stopped. – Mathew Aug 30 '17 at 07:17
  • Yes you can, use the data collected from the `onLocationChanged` to get your location every time you need it. – Orvenito Aug 30 '17 at 07:23