Finding my current Position in Java - java

I've never used the android packages before, and I just want to get my current position. After looking online a bit, I've gotten this far.
import android.location.Location;
import android.location.LocationManager;
import android.content.*;
public class CurPosGetter{
public static double[] getPosition(){
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = (Location) lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
double[] ans = new double[2];
ans[0] = latitude;
ans[1] = longitude;
return ans;
}
public static void main (String [] args){
double[] pos = getPosition();
System.out.println(pos[0] + " , " + pos[1]);
}
}
The problem is at the 'getSystemService' line: by reading the javadocs for Context I understand that by calling this method in conjunction with Context.LOCATION_SERVICE I can get my current position, but I don't really understand how to call getSystemService. Any help would be appreciated, I'm sure this is a simple issue and I just don't understand the classes I'm using.

getSystemService() is a method of the Context class. Your class does not subclass Context. Generally you would use getSystemService() in an Activity (which is a subclass of Context).

I think your referring to a compiler error saying something like "method getSystemService not found". The getSystemService is held with the Context class which is obtained in your Application. Check out this post to see how to get Context.
Static way to get 'Context' on Android?

Here is the overview of location services in Android. Here is the LocationManager class at the heart of location services in Android.
Here is an Android developer tutorial on "Location Strategies". Here is another tutorial that might be usable.
Also, you cannot just ask Android for your current position, since GPS may take quite some time to get a fix. Instead, you need to request location updates and use the first update you get, or similar patterns.

Try this working code, tested in SEMC Xperia Play
public class CLASSNAME extends Activity //Use your class name(It will done automatically in eclipse when you start a project)
{
private LocationManager
locationManagerNetwork;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManagerNetwork = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
android.location.Location location2 = locationManagerNetwork.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location2 != null)
{
String message = String
.format("Yout location : \n Longitude: %1$s \n Latitude: %2$s",
location2.getLongitude(), location2.getLatitude());
File sdcard = Environment.getExternalStorageDirectory();
{
try
{
FileWriter filenew = new FileWriter(sdcard + "/FOLDERNAME/network.txt");
//Use your folder name
BufferedWriter bw = new BufferedWriter(filenew);
bw.write(message);
bw.close();
}
catch (IOException e)
{
}}}}}

Related

Unable to clear mock location?

This is how I set a mock location in my app:
public void startMockLocation(String latitude, String longitude){
FusedLocationProviderClient locationProvider = new FusedLocationProviderClient(getApplicationContext());
locationProvider.setMockMode(true);
Location loc = new Location("gps");
mockLocation = new Location("gps");
mockLocation.setLatitude(Double.valueOf(latitude));
mockLocation.setLongitude(Double.valueOf(longitude));
mockLocation.setAltitude(loc.getAltitude());
mockLocation.setTime(System.currentTimeMillis());
mockLocation.setAccuracy(1f);
mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mockLocation.setBearingAccuracyDegrees(0.1f);
mockLocation.setVerticalAccuracyMeters(0.1f);
mockLocation.setSpeedAccuracyMetersPerSecond(0.01f);
}
locationProvider.setMockLocation(mockLocation);
}
However I wasn't able to clear the mock location and set the real location back using this code below. What should I write instead?
public void clearMockLocation() {
locationProvider.setMockMode(false);
}
as i see your code , you are calling two methods one to set mock location and other to disable it but in other method i am not sure which object of location provider you are using , i would prefer you to declare a global object of location provider and use it anywhere
FusedLocationProviderClient locationProvider;
public void startMockLocation(String latitude, String longitude){
locationProvider = new FusedLocationProviderClient(getApplicationContext());
locationProvider.setMockMode(true);
Location loc = new Location("gps");
mockLocation = new Location("gps");
mockLocation.setLatitude(Double.valueOf(latitude));
mockLocation.setLongitude(Double.valueOf(longitude));
mockLocation.setAltitude(loc.getAltitude());
mockLocation.setTime(System.currentTimeMillis());
mockLocation.setAccuracy(1f);
mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mockLocation.setBearingAccuracyDegrees(0.1f);
mockLocation.setVerticalAccuracyMeters(0.1f);
mockLocation.setSpeedAccuracyMetersPerSecond(0.01f);
}
locationProvider.setMockLocation(mockLocation);
}
then in other method
public void clearMockLocation() {
if(locationProvider!=null){
locationProvider.setMockMode(false);
if(mockLocation!=null){
mockLocation.setLatitude(real_latitude);
mockLocation.setLongitude(real_longitude);
mockLocation.setAltitude(real_altitude);
mockLocation.setTime(System.currentTimeMillis());
mockLocation.setAccuracy(1f);
mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mockLocation.setBearingAccuracyDegrees(0.1f);
mockLocation.setVerticalAccuracyMeters(0.1f);
mockLocation.setSpeedAccuracyMetersPerSecond(0.01f);
}
locationProvider.setMockLocation(mockLocation);
}
}
}
Update:
As far, your problem is following these steps such as:
Setting your mock location for Gps
Going to GoogleMaps and see your mock location
Turn back your app and want to stop mocking
Here I am giving you some techniques to disable mock locations.
Method.1
Spoofing or faked locations can be avoided by using the Location Manager's API.
For this you first have to import the google play services LocationServices (must visit) API:
You need to import:
import com.google.android.gms.location.LocationServices;
And in App-level build.gradle:
implementation 'com.google.android.gms:play-services-location:17.0.0'
Your Class must implement these interfaces:
public class TestMapsActivity extends FragmentActivity implements OnMapReadyCallback,
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener { ...}
Then, you need to Override these methods such as:
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
Now, We can remove the test provider before requesting the location updates from both the providers (Network or Gps):
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
Log.d(TAG ,"Removing Test providers")
locationManager .removeTestProvider(LocationManager.GPS_PROVIDER);
} catch (IllegalArgumentException error) {
Log.d(TAG,"Got exception in removing test provider");
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
Now, If you look into the Android documentation of the LocationManager:
removeTestProvider() throws
IllegalArgumentException if no provider with the given name exists
You will get a better intuition from this android-issue. For that specific thread, You can try using Criteria.ACCURACY_FINE instead of LocationManager.GPS_PROVIDER such as:
LocationManager locationManager = (LocationManager)context.getSystemService( Context.LOCATION_SERVICE );
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String locationprovider = locationManager.getBestProvider(criteria, true);
if ( locationprovider == null ) {
Log.e(TAG, "location provider is not available.!");
return;
}
Method.2
If the above method still doesn't work for you, you can silently enable /disable mock settings as follows:
// disable mocking.
Settings.Secure.putString(getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION, "0");
You can also get better intuition here and here.
Method.3
There is another way you can do that to get an accurate understanding whether GPS/Network providers are enabled or not:
ContentResolver contentResolver = context.getContentResolver();
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
boolean networkEnabled = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.NETWORK_PROVIDER);
Other Steps to follow.
You should have to follow these steps to clear/reset your mock location such as:
Enable mock locations in the development panel in your settings.
Add permissions to your Manifest.xml i.e.
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
Now again open GoogleMaps, and wait until the Gps provider to receive a new realtime-location. It could be a bit of time-consuming i.e. (1-3 minutes).
So while removing the provider, just let the Gps receive a new fresh location, then it will be resolved and fixed. If in case, it is not working again, then you can further do these steps:
Go to the app settings, Clear the App-Cache and Restart the Mobile
Device.
I hope that it would work really fine. You can also visit these references to get better intuition:
Android-mock-location-on-device
Remove-mock-location

How to remove FusedlocationProviderClient location updates from within non-activity class

I’m trying to write a utility class to wrap the Google Play Services FusedLocationProviderClient API and location permissions request as I’m sick of writing all that boilerplate every time I want to add location functionality to an app. The problem I’m having though is I’m unable to remove location updates once I’ve started them. Here’s the relevant bits of my utility class:
public class UserLocationUtility extends LocationCallback
{
// Hold a WeakReference to the host activity (allows it to be garbage-collected to prevent possible memory leak)
private final WeakReference<Activity> weakActivity;
// Debug tag
private static final String TAG = "UserLocationUtility";
public static class RequestCodes
{
static final int CURRENT_LOCATION_ONE_TIME = 0;
static final int CURRENT_LOCATION_UPDATES = 1;
static final int LAST_KNOWN_LOCATION = 2;
static final int SMART_LOCATION = 3;
}
private FusedLocationProviderClient mLocationClient;
private Context mContext;
private LocationRequest mLocationRequest;
/* Constructor */
UserLocationUtility(Activity activity){
// assign the activity to the weak reference
this.weakActivity = new WeakReference<>(activity);
// Hold a reference to the Application Context
this.mContext = activity.getApplicationContext();
// Instantiate our location client
this.mLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
// Set up the default LocationRequest parameters
this.mLocationRequest = new LocationRequest();
setLocationRequestParams(2000, 500, LocationRequest.PRIORITY_HIGH_ACCURACY);
// Sets up the LocationRequest with an update interval of 30 seconds, a fastest
// update interval cap of 5 seconds and using balanced power accuracy priority.
} /* Note: values for testing only. Will be dialed back for better power management when testing complete */
/* Stripped out other methods for brevity */
#SuppressLint("MissingPermission")
public void getCurrentLocationOneTime(final UserLocationCallback callback){
mLocationClient.requestLocationUpdates(mLocationRequest, new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult){
if (locationResult == null){
callback.onFailedRequest("getCurrentLocationOneTime(): Request failed: returned null");
return;
}
callback.onLocationResult(locationResult.getLastLocation());
stopLocationUpdates(); /* Stopping location updates here just for testing (NOT WORKING!!) */
}
}, null);
}
public void stopLocationUpdates(){
mLocationClient.removeLocationUpdates(new LocationCallback(){});
Log.i(TAG, "stopLocationUpdates(): Location updates removed");
}
}
Here’s how I’m trying to use it (from MainActivity):
UserLocationUtility locationUtility;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationUtility = new UserLocationUtility(this);
if (locationUtility.checkPermissionGranted()){
Log.i(TAG, "Permissions are granted.");
getLocationUpdates();
} else {
Log.i(TAG, "Permissions are not granted. Attempting to request...");
locationUtility.requestPermissions(UserLocationUtility.RequestCodes.CURRENT_LOCATION_UPDATES);
}
}
public void getLocationUpdates(){
locationUtility.getCurrentLocationOneTime(new UserLocationCallback() {
#Override
public void onLocationResult(Location location) {
Log.i(TAG, "getLocationUpdates result: " + location.toString());
}
#Override
public void onFailedRequest(String result) {
Log.e(TAG, "LocationUpdates result: " + result);
}
});
}
And here's a sample from the log:
I/MainActivity: getLocationUpdates result: Location[fused 34.421998,-125.084000 hAcc=731 et=+2h10m52s694ms vAcc=??? sAcc=??? bAcc=???]
I/UserLocationUtility: stopLocationUpdates(): Location updates removed
I/MainActivity: getLocationUpdates result: Location[fused 34.421998,-125.084000 hAcc=739 et=+2h10m57s697ms vAcc=??? sAcc=??? bAcc=???]
I/UserLocationUtility: stopLocationUpdates(): Location updates removed
I/MainActivity: getLocationUpdates result: Location[fused 34.421998,-125.084000 hAcc=763 et=+2h11m5s723ms vAcc=??? sAcc=??? bAcc=???]
I/UserLocationUtility: stopLocationUpdates(): Location updates removed
etc...
As you can see I’m receiving the location updates correctly but the call to stopLocationUpdates() isn’t working. I have a feeling it’s something to do with the fact that I’m passing a new LocationCallback to the removeUpdates() method, but I’m not sure what the alternative is, or even if there is an alternative. This being a non-activity class I can’t exactly initialise LocationCallback as a member in onCreate() then pass it around as needed. The google docs on this aren’t much help at all. Whether that’s because I lack the necessary understanding to decipher them or because they’re just not very good I don’t know but either way I’m stumped and having searched around a lot I can’t seem to find an existing answer elsewhere.
Thanks.
Posting my solution as an answer in case it helps anyone else.
I got it working by declaring a LocationCallback as a member variable and then initialising (or re-initialising) it in each method that requires it...
public void getCurrentLocationUpdates(final UserLocationCallback callback){
if (mIsReceivingUpdates){
callback.onFailedRequest("Device is already receiving updates");
return;
}
// Set up the LocationCallback for the request
mLocationCallback = new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult){
if (locationResult != null){
callback.onLocationResult(locationResult.getLastLocation());
} else {
callback.onFailedRequest("Location request returned null");
}
}
};
// Start the request
mLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
// Update the request state flag
mIsReceivingUpdates = true;
}
I check at the beginning of the method whether or not location updates are already being received and get out early if so. This prevents duplicate (and thus unstoppable) location update requests being initiated.
Calling the stopLocationUpdates (below for reference) method now works as it should.
public void stopLocationUpdates(){
mLocationClient.removeLocationUpdates(mLocationCallback);
mIsReceivingUpdates = false;
Log.i(TAG, "Location updates removed");
}

Using json and location to display data from a Weather API

I am trying to request a JSON froM a url to get specific data as shown below using separate java class.
package com.example.user.test4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
/**
* Created by user on 05/12/2017.
*/
public class Parser {
// the below line is for making debugging easier
final String TAG = "Parser.java";
// where the returned json data from service will be stored when downloaded
static String json = "";
public String getJSONFromUrl(String url) {
//// TODO: 05/12/2017 https://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java
try {
// this code block represents/configures a connection to your REST service
// it also represents an HTTP 'GET' request to get data from the REST service, not POST!
URL u = new URL(url);
HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
restConnection.setRequestMethod("GET");
restConnection.setRequestProperty("Content-length", "main");
restConnection.setRequestProperty("Content-length", "sys");
restConnection.setRequestProperty("Content-length", "weather");
restConnection.setUseCaches(false);
restConnection.setAllowUserInteraction(false);
restConnection.setConnectTimeout(10000);
restConnection.setReadTimeout(10000);
restConnection.connect();
int status = restConnection.getResponseCode();
// switch statement to catch HTTP 200 and 201 errors
switch (status) {
case 200:
case 201:
// live connection to your REST service is established here using getInputStream() method
BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));
// create a new string builder to store json data returned from the REST service
StringBuilder sb = new StringBuilder();
String line;
// loop through returned data line by line and append to stringbuilder 'sb' variable
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
// remember, you are storing the json as a stringy
try {
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String containing data to activity (or whatever your activity is called!)
return json;
}
// HTTP 200 and 201 error handling from switch statement
} catch (MalformedURLException ex) {
Log.e(TAG, "Malformed URL ");
} catch (IOException ex) {
Log.e(TAG, "IO Exception ");
}
return null;
}
}
Then in another another activity I am getting longitude and latitude and bind it to text to display it:
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
// Use GPS provider to get last known location
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if (lastKnownLocation == null)
{
// if no last location is available set lat/long to Lincoln Location
lat = 53.228029;
longi = -0.546055;
}
else
{
// if last location exists then get/set the lat/long
lat = lastKnownLocation.getLatitude();
longi = lastKnownLocation.getLongitude();
}
Afterwards I send information to another application using this code and start the activity:
public void sendLocation(View view) {
Intent coordinates = new Intent(this,MainActivity.class);
coordinates.putExtra("lat", lat);
coordinates.putExtra("longi", longi);
startActivity(coordinates);
}
Then in the main activity I am trying to receive data and display it yet I caught and issue that the data is either not sent or received yet when the latitude and longitude are set in the following code to 0 the lat and longi are still classified as null and display and error message.
public void getCoordinates(View view) {
// FIXME: 05/12/2017
final Button coordinates = (Button) findViewById(R.id.getCoordinates);
final Button displayData = (Button) findViewById(R.id.displayData);
coordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getLocation = MainActivity.this.getIntent();
extras = getLocation.getExtras();
lat = extras.getDouble("lat");
longi = extras.getDouble("longi");
//Checking if there is data stored in the doubles, if not the user will be warned
if (lat == null && longi == null) {
Toast.makeText(MainActivity.this, "No Data recorded, please use permissions", Toast.LENGTH_SHORT).show();
} else {
displayData.setVisibility(View.VISIBLE);
}
The application is supposed to use the collected latitude and longitude to access url and display the weather data but as I don't get any lat/longi I cannot show anything.
I am sorry for the amount of code but I have no clue at which point I have managed to make a mistake so hopefully someone will be able to help.
Thanks.
I see a couple of issues, but it's been a while since I messed with Android java.
Why are you passing a View to SendLocation() and getCoordinates()? Each Activity should control their own screen usage.
You retrieve your MainActivity intent inside an onClick() handler. Instead, this should be in the main line, either from OnCreate(), onNewIntent(), etc. My guess is that this is the cause of your issue. If you capture the MainActivity Intent() at the start of this activity, you can control whether to continue processing or not (if 0's are passed for example).
Also, you don't show how any of these Activity's or the getJSONFromURL class are invoked, which could have an impact on what you see.
HTH, Jim

GPS Coords being always 0.0-0.0 using LocationListener in a Android App

I need to develop an app for android for a university task and a part of it consists in sending the GPS coords of the device to my database. Here's the class that I'm using to get the coords
public class MyLocationListener implements LocationListener {
double latitude;
double longitude;
public MyLocationListener(Context myContext){
LocationManager locationManager = (LocationManager) myContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public double getLatitude(){
return latitude; }
public double getLongitude(){
return longitude; }
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
That is called inside InterfaceActivity.java, using this:
MyLocationListener ggwp = new MyLocationListener(InterfaceActivity.this);
HttpDevices elenco = new HttpDevices(LoginIstance.getIst().getLog()[0],LoginIstance.getIst().getLog()[1],LoginIstance.getIst().getID(),String.valueOf(ggwp.getLatitude()),String.valueOf(ggwp.getLongitude()));
And finally HttpDevices is an asynttask that "runs" http messages to my database, using this code:
HttpPost httppost = new HttpPost("http://88.116.86.82/android/remote/connessione.php?user="+usr+"&pass="+pss+"&id="+id+"&lat="+lat+"&long="+log);
But the coords send to the database are always 0.0 - 0.0 , and I can't even try the code an debug it on the emulator ( blue stack ) because it doesn't have gps coords. Tried it on my Moto G but they are just 0. I tried spamming that string (connessione.php etc.. ) in my broweser giving random values for lat and long and yes, it works. It updates the database and shows the coords in my app, so the problem should be in the java. Any tips? I've searched alot in google/stackoverflow and didnt' find anything, it's the first time I encouter a problem that requires me to post here. Hope you can help me! Thank youu!
Edit: in case you want to take a look at my whole code there is a github link:
https://github.com/leejaku/RemoteAndroid2
I just try to get through your code... Please correct me if I have missed something
If I look at your HttpDevices Class you try to send your Data like this...
lat = String.valueOf(MyLocationListener.latitude);
log = String.valueOf(MyLocationListener.longitude);
This will try to get the value of a class property which is 0.0, because it is not the instance of MyLocationListener that is updating the lat and long... you need to create a Singleton of MyLocationListener to get one single sharedInstance of your listener, or you have to do it with a Delegate Pattern, or you save the Values to SharedPreferences...
Do you have enough knowledge of Java to build one of these Paradigms, and does it make sense to you? (Sorry for that Question, I don't know how good you are mate :-)...) Otherwise I could write you something to solve it
UPDATE
Well this problem seems to be nasty, so we will need a "NastyLocationListener" to solve it, and thank Neo has written the ultimate one ;-)
Checkout this Class
https://gist.github.com/DennisWeidmann/de2ebb2b2549a938fa50
Usage just like this
/////////Just to know it
Log.e("lati", NastyLocationListener.getLatitude(this)); //On most phones you can use the Listener without any other Code
Log.e("longi", NastyLocationListener.getLongitude(this)); //It uses Androids native cached location but this is not updated proper
/////////Just to know it end
/////////Normal usage
nastyLocationListener = new NastyLocationListener(this); //In your MainActivity instanciate a NastyLocationListener (its only needed once... All other Activities could get data from him)
nastyLocationListener.startListening(); //It starts listening to Location Updates and triggers the Location Provider to fetch updates (its bool, true if almost one Provider is available, false if no Provider is available)
nastyLocationListener.stopListening(); //Use this line when you pause the app, or quit it... it will stop the listener and could be resumed with startListening()
NastyLocationListener.getLatitude(this); //Could be used in every class, on every time, however you want without any other code like above
NastyLocationListener.getLongitude(this); //Could be used in every class, on every time, however you want without any other code like above
/////////Normal usage end
UPDATE
Screenshot of your App on my device without changing any code instead of the REST Call, I have inserted a Log to output my Latitude..
Try with this class, it's from my github account: https://github.com/chiiiky14/GPStracker
Import it to your project and create the object:
GPSTracker gpstracker = new GPSTracker(context);
And after that:
gpstracker.getLatitude();
gpstracker.getLongitude();
Just make sure the GPS of your device is already activate. Hope this will help.

`locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);` always returns true

I am testing an app which uses Location services. And it returns null causing NPE (Null Pointer Exception) whenever my Location Services are turned off. So after some searching I found that
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
should return the correct boolean value but when testing my app it seems to always return true causing a NPE (Null Pointer Exception) and crashing my app.
I also read this question. Which has the exact opposite problem apparently and tried that solution. That also didn't work. I am testing on a Samsung G5. Why is this happening. Is something wrong in the code or is there another solution to my problem.
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isGPSEnabled = false;
intentThatCalled = getIntent();
String m2txt = intentThatCalled.getStringExtra("v2txt");
getLocation(m2txt);
}
public void getLocation(String n2txt) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
location = locationManager.getLastKnownLocation(bestProvider);
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
if (isGPSEnabled==true) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(PlacesDecoder.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(n2txt);
}
}
I am still a beginner in android.
Please do help.
EDIT:
This question seems to have the same problem on the same Hardware model. Is this a Hardware Bug? If it is, is there any other possibility. I will also test on another device Note-4 and let you know.
The solution to your problem is to NEVER assume you have a location, Just because your GPS is enabled does not mean you will get a location.
At any time you can get a null location so instead of worrying about if the GPS is enabled or not you should worry about if your location returned is null or not.
getLastKnownLocation() can return a null if there is no last location

Categories

Resources