0

I am testing my app on a real device and getting a null location when the GPS is on. When I test on the emulator with dummy coordinates it works fine. What is wrong?

locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
listener = new MyLocationListener();
viaGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
viaNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!viaGps && !viaNetwork) {
    tracking = false;
} else {
    if (viaGps) {
        Log.d("", "gps is on");
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }else if (viaNetwork) {
        Log.d("", "network is on");
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    if (location == null) {
        Log.d("", "location not fouond");
    }
thegrinner
  • 11,546
  • 5
  • 41
  • 64
Usman Riaz
  • 2,920
  • 10
  • 43
  • 66

2 Answers2

0

You need a Location listener:

Follow the documentation

Update:

You can also try that easy way: What is the simplest and most robust way to get the user's current location in Android?

Community
  • 1
  • 1
madlymad
  • 6,367
  • 6
  • 37
  • 68
0

Try using this , it solved my problem

  double latitude = gps.getLatitude();
  double longitude = gps.getLongitude(); 

Also check your permission

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
  <uses-permission android:name="android.permission.INTERNET"></uses-permission>
madlymad
  • 6,367
  • 6
  • 37
  • 68
MRX
  • 1,400
  • 3
  • 12
  • 32