我正在使用谷歌的FusedLocationClient
检索LastKnowlocation
并将userLocality
和userCountry
存储为中的两个字符串>OnsuccesListener
匿名内部类。
在下面的代码中:locationProvidedTextView
中的文本设置是正确的(因此userLocality
和userCountry
获取一些值)但是当我尝试时要在内部类之外打印字符串值,它们都会以某种方式变成 null
。
这可能是一个愚蠢的问题,但是我做错了什么?我需要在另一个 OnclickListener
方法中使用这些值。
代码 fragment :
// GlOBAL VARIABLES
....
private String userCountry;
private String userLocality;
@Override
protected void onCreate(Bundle savedInstanceState) {
....
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder
.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0) {
if (addresses.size() > 0) {
userLocality = addresses.get(0).getLocality();
userCountry = addresses.get(0).getCountryName();
locationProvidedTextView.setText("Your address: " + userLocality + ", " + userCountry);
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
// HERE BOTH STRINGS BECOME NULL
System.out.println("ADDRESS1 ======= " + userLocality);
System.out.println("ADDRESS2 ======= " + userCountry);
....
}
最佳答案
获取位置需要一些时间。根据您的代码,您将立即打印 mFusedLocationClient.getLastLocation().addOnSuccessListener
您的听众不会立即接到电话。因此您不会从这些字符串中获得任何值。
更好的实现方法是,在另一个类中执行所有与位置相关的操作,而不是在 onCreate 中。得到结果后,使用接口(interface)
获取结果。
关于java - 字符串在匿名内部类之外变为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45881957/