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

标签 java android anonymous-inner-class

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

在下面的代码中:locationProvidedTextView中的文本设置是正确的(因此userLocalityuserCountry获取一些值)但是当我尝试时要在内部类之外打印字符串值,它们都会以某种方式变成 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/

相关文章:

java - OO设计-公共(public)API方法实现

android - 无法初始化 GoogleMap,返回 null

java - 递归队列方法1(-1)

java - 抽象类错误 : Exception in thread "main" java. lang.NullPointerException

Android WebView navigator.getCurrentPosition 问题

java - 这两个匿名类的声明有什么区别

java, 反射, 内部类,

Java,匿名内部私有(private)接口(interface)的可访问性

java - 线程 "AWT-EventQueue-0"java.lang.NumberFormatException 中出现异常

java - Hibernate_sequence 表生成