0

I have got a small problem, my GPS Tracker keeps asking for activating Location while i activate it. I analysed and reanalysed my class but can't find my error...

Someboy care to help?

GPSTracker.java

public class GPSTracker extends Service implements LocationListener {

private final Context context;

Location location;

boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;

double latitude;
double longitude;

private static final long MinDistanceChangeUpdate = 10;
private static final long MinTimeUpdate = 1000 * 60 * 1;

protected LocationManager locationManager;

public GPSTracker(Context context){
    this.context = context;
    getLocation();
}

public Location getLocation(){
    try{
        locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if(!isNetworkEnabled && !isGPSEnabled){

        }else{
            this.canGetLocation = true;

            if(isNetworkEnabled){
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);

                if(locationManager != null){
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if(location != null){
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }


            if(isGPSEnabled){
                if(location == null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);

                    if(locationManager != null){
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if(location != null){
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

            }
        }

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

    return location;
}

public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }
    return latitude;
}

public double getLongitude (){
    if(location != null){
        longitude = location.getLongitude();
    }
    return  longitude;
}

public boolean canGetLocation(){
    return this.canGetLocation;
}

public void showSettingsAlert(){
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
    alertDialog.setTitle("GPS is Settings! ");
    alertDialog.setMessage("GPS is not enable, Wanna enable?");

    alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(intent);
        }
    });

    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    alertDialog.show();
}


@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

MainActivity.java

public class MainActivity extends Activity {

Button btnshowLocation;

GPSTracker gps;

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

    btnshowLocation = (Button)findViewById(R.id.showLocation);
    btnshowLocation.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            gps = new GPSTracker(MainActivity.this);

            if(gps.canGetLocation()){
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();

                Toast.makeText(getApplicationContext(), "Latitude = " + latitude + "  Longitude = " + longitude, Toast.LENGTH_LONG).show();
            } else {
                gps.showSettingsAlert();
            }

        }
    });
  }



}

Stracktrace

java.lang.NullPointerException: Attempt to invoke virtual method      'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on   a null object reference
04-26 23:55:51.943  21374-21374/com.example.dell.exampleapplication  W/System.err﹕ at  android.content.ContextWrapper.getSystemService(ContextWrapper.java:582)
 04-26 23:55:51.943  21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.GPSTracker.getLocation(GPSTracker.java:44)
04-26 23:55:51.943  21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.GPSTracker.<init>(GPSTracker.java:39)
04-26 23:55:51.943  21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.MainActivity$1.onClick(MainActivity.java:28)

Edit : Added Stracktrace Thanks in advance,

1 Answers1

0

Funny to see a snippet of some code I posted a long time ago in an SO answer :-D Location servise GPS Force closed

Many things has happened since then and my recommendation these days is to use https://github.com/mcharmas/Android-ReactiveLocation

Mainly because:

  1. It uses the Fused location (more battery efficient + better accuracy)
  2. Way less boilerplate code
  3. Additional power of RxJava (no need to dive into details about RxJava for simple usage but it has some awesome features)
  4. I added Activity Recognition to the library (so I like to advertise how awesome I think it is)

To get most recent location the only code you need to write is:

ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
    .subscribe(new Action1<Location>() {
        @Override
        public void call(Location location) {
            doSthImportantWithObtainedLocation(location);
        }
    });

To vaguely answer your question, my suspicion is that perhaps you have GPS turned on but not WiFi location (just guessing though).

If you are determined to use the code you posted, then I would suggest adding various Log outputs to debug the situation. Something like:

public Location getLocation(){
    try{
        locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if(!isNetworkEnabled && !isGPSEnabled){
             Log.e("GPSTracker", "!isNetworkEnabled && !isGPSEnabled");
             Log.e("GPSTracker", "is network location enabled: " + isNetworkEnabled );
             Log.e("GPSTracker", "is GPS location enabled: " + isGPSEnabled);
        }else{
            this.canGetLocation = true;

            if(isNetworkEnabled){
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);

                if(locationManager != null){
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if(location != null){
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }


            if(isGPSEnabled){
                if(location == null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);

                    if(locationManager != null){
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if(location != null){
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

            }
        }

    }catch(Exception e){
        Log.e("GPSTracker", "error getting location", e);
        e.printStackTrace();
    }

    return location;
}

Otherwise pose less restrictive constraints on the canGetLocation boolean (as it is really that variable that is causing you problems)

Changing:

    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if(!isNetworkEnabled && !isGPSEnabled){

    }else{
        this.canGetLocation = true;
        ...

To

    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    this.canGetLocation = isNetworkEnabled || isGPSEnabled;

    if(!isNetworkEnabled && !isGPSEnabled){

    }else{
        ...
Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
  • I tried your suggestions however it didn't work, i added the stacktrace in an edit if you can take a look please – user3485829 Apr 26 '15 at 22:00
  • try and change `locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);` to `locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE)` – cYrixmorten Apr 26 '15 at 22:14
  • It stopped asking for the rights thank you for that, seems my code still has some errors since latitude and longitude output is 0.0.. – user3485829 Apr 26 '15 at 22:19
  • may very well be that lastKnownLocation is null .. try opening google maps and let it fix your location, then open your app after. – cYrixmorten Apr 26 '15 at 22:31
  • thank you, needed to add permissions in manifest, however tracking based on GPS is not very precise.. do you agree? – user3485829 Apr 26 '15 at 22:38
  • Actually, the code you use seems to not use GPS at all, because it first tries to get location based on network and then if that fails - via GPS. So you most likeliy are not even getting GPS locations. Secondly fetching a single location once a while does not give it a chance to 'tune in' so to speak. Usually GPS precision lies in the area of 1 - 10m depending on the surroundings. – cYrixmorten Apr 27 '15 at 08:49
  • I think it uses both GPS and Location, cause when i have high precision turned on (in Location), it works fine. However when it's either only GPS, or only WiFi, then it crashes. Gotta fix this ! – user3485829 Apr 27 '15 at 09:56
  • It does only use GPS if network did not get a location: ` if(isGPSEnabled){ if(location == null){ .. }` – cYrixmorten Apr 27 '15 at 10:04
  • But I will strongly encourage you to try out the ReactiveLocation library. Will save you a lot of headaches and it just works (at least in my experience). – cYrixmorten Apr 27 '15 at 10:07
  • Thanks for sharing your experience, thoughts and knowledge !! However i would like to stick to this for now, since i am new in Location Based Services. Trying out the different possibilities :) – user3485829 Apr 27 '15 at 11:02