的外空与谷歌的FusedLocationClient
和OnsuccesListener
匿名内部类存储userLocality
和userCountry
两个字符串。字符串将成为我检索<code>LastKnowlocation</code>匿名内部类
在下面的代码:文本集是在locationProvidedTextView
正确的(因此userLocality
和userCountry
得到一些值),但是当我尝试打印内部类以外的字符串值,它们在某种程度上都成为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);
....
}
事实上,在听众有机会接听电话之前,您似乎正在打印这些值,即使您先声明了它。 – Berger
'getLastLocation()'似乎是一个异步调用。添加几个断点,你会看到如何工作 – Pelocho
'OnSuccess(Location location)'将被异步调用。你的值是'null',因为在值被分配到'onSuccess()'方法之前,这些值将是空的。 – Wizard