Excuse me for the basic question but I am learning android programming now.
I am using GoogleFusedProviderClient to get the location of the app from a custom class. I have put it in a class as I need to call this from multiple activities.
fas class:
public class fas {
// get the context from the Activity that uses this class
private Context context;
// Vars to store GPS info
public Double latitude, longitude;
public Float accuracy;
private FusedLocationProviderClient flpc;
fas_functions(Context context) {
this.context = context;
}
public void getAppLocation() {
flpc = LocationServices.getFusedLocationProviderClient(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Already forced user to enable location
return;
}
flpc.getLastLocation().addOnSuccessListener((Activity) context,
new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
} else {
// No position so request an immediate one
startListener();
}
}
});
}
On my Activity I call getAppLocation() to get the location and then try to use Fas.latitude
and Fas.longitude
. This is where I am getting a null pointer exception and do not understand the reason.
Activity:
public class Activity extends AppCompatActivity {
.......
// Import Class fas_functions
fas_functions Fas = new fas_functions(this);
........
private void function check_loc() {
Fas.getAppLocation();
// This will return null and if I use this in Volley for example it will throw a NullPointerException
System.out.println(Fas.latitude);
}