Reputation: 984
In my activity I need to get the current location of the mobile phone using gps. I have used the following code:
Location gpslocation;
LocationManager lmanager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
gpslocation= lmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//error in the next line as follows java.lang.nullpointerexception
gpslatitude=gpslocation.getLatitude();
gpslongitude=gpslocation.getLongitude();
I know that getlastknownlocation will fetch the last location in which the gps was fixed. In this case getlastknownlocation is returning a null pointer. That's why the exception arises and my app force closes. Also I know that there is another method for getting the gps coordinates using onlocationchanged. But for this to work the device has to be in a moving situation for some distance. Since in my app I want to get the gps coordinates in a stationary manner, Is there any other way to get the gps coordinates using gps in android.
I don't want to use network provider because it would only give the coordinates of places which is about 5 kms distance from the actual position of my current location. So I wouldn't encourage the use of network location in my app. Since 5 km distance is not an acceptable range for me. Is there any other way for fixing the gps coordinates using code. And there by when using the lastknownlocation would fetch me an solution to my application.
Upvotes: 0
Views: 1482
Reputation: 1039
Some devices doesn't support getLastKnownLocation (e.g. my Motorola XT720). You have to implement LocationListener and save location updates in onLocationChanged by yourself to database or sharedpreferences. And when getLastKnownLocation is null use that saved location.
EDIT: Main problem with that approach is that when user moves a lot it isn't accurate. Another solution will be to write a service witch fires e.g. once a hour location manager, saves results and then you will have your "last location" updated every hour on older devices.
Upvotes: 1