字符串在匿名内部类之外变为 null



我正在使用谷歌的FusedLocationClient检索LastKnowlocation,并将userLocalityuserCountry存储为两个字符串OnsuccesListener匿名内部类中。

在下面的代码中:文本集在locationProvidedTextView中是正确的(因此userLocalityuserCountry得到一些值(,但是当我尝试在内部类之外打印字符串值时,它们不知何故都变得null

这可能是一个愚蠢的问题,但我做错了什么?我需要在另一种OnclickListener方法中使用这些值。

代码片段:

// 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获得结果后获得结果。

问题是您没有构建任何用于检索值的机制。换句话说,您的onCreate现在看起来像这样:

onCreate{
// set listener
// print stuff out
}

这些值是在侦听器被调用后设置的,但此时你已经完成了onCreate方法。

这是正常的。

我不知道你的代码,但似乎addOnSuccessListener是一种异步机制。

因此,您希望在异步部分外部显示尚未设置的值。

换句话说,您尝试显示尚未设置的值。

要对此进行测试,您可以输入: 在 addOnSuccessListener a 中:

System.out.println("User locality found");

您将看到该消息可能出现在

System.out.println("ADDRESS1 ======= " + userLocality);
@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();
}

我想这种方法每次根据GPS准确获取绳索时都会将数据设置为userLocality和userCountry,但是当GPS被禁用或网络不强时,它可能会给出错误的读数,这可能会导致在这里获得空字符串变量,您应该尝试更改提供商以及网络或GPS提供商的准确性,这可能会有所帮助。

最新更新