【发布时间】:2017-08-25 12:55:52
【问题描述】:
我正在使用谷歌的FusedLocationClient 检索LastKnowlocation,并将userLocality 和userCountry 作为两个字符串存储在OnsuccesListener 匿名内部类中。
在下面的代码中:locationProvidedTextView 中的文本集是正确的(因此 userLocality 和 userCountry 得到一些值)但是当我尝试在内部类之外打印字符串值时,它们不知何故都变成了 @ 987654329@。
这可能是一个愚蠢的问题,但是我做错了什么?我需要在另一个 OnclickListener 方法中使用这些值。
代码sn-p:
// 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);
....
}
【问题讨论】:
-
事实上,即使您先声明了它,您也似乎在侦听器有机会被调用之前打印了这些值。
-
getLastLocation()似乎是一个异步调用。添加几个断点,您将看到它是如何工作的 -
OnSuccess(Location location)将被异步调用。您的值是null,因为在将值分配给onSuccess()方法之前,这些值将为空。
标签: java android anonymous-inner-class