【发布时间】:2018-12-23 09:25:36
【问题描述】:
请原谅我的基本问题,但我现在正在学习 android 编程。
我正在使用 GoogleFusedProviderClient 从自定义类中获取应用的位置。我把它放在一个类中,因为我需要从多个活动中调用它。
fas 类:
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();
}
}
});
}
在我的活动中,我调用 getAppLocation() 来获取位置,然后尝试使用 Fas.latitude 和 Fas.longitude。这是我得到一个空指针异常并且不明白原因的地方。
活动:
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);
}
【问题讨论】:
标签: android android-studio nullpointerexception location fusedlocationproviderclient