我想从我的 test()
方法中的 onLocationChanged
方法访问纬度和经度变量。
class MainActivity
{
private IALocationManager mIALocationManager;
Double lat;
Double lng;
private IALocationListener mLocationListener = new IALocationListenerSupport()
{
@Override
public void onLocationChanged(IALocation location)
{
lat = location.getLatitude();
lng = location.getLongitude();
Log.d(TAG, "location is: " + location.getLatitude() + "," + location.getLongitude());
}
}
public void test()
{
Log.d(TAG, "Latitude = " + lat);
Log.d(TAG, "Longitude = "+ lng);
}
}
从上面的代码中,我得到的输出是
//From onLocationChanged
location is: 2.8081944950315636,101.75935307113596
//From test()
Latitude = null
Longitude = null
我可以在 onLocationChanged
方法中获取位置,但变量不会存储到 lat
和 lng
中,也无法调用通过 test()
方法。
我可以知道如何解决这个问题吗?是否可以将变量从一种方法传递到另一种方法?
最佳答案
问题是因为变量 lat
Latitude 和 lng
Longitude 仅在调用 onLocationChanged
时才被分配变量。因此,如果您在调用 onLocationChanged
之前调用您的 test()
方法,则 lat
和 lng
的值不会尚未分配且没有任何值(value)。
所以解决方案是在 onLocationChanged
中调用方法 test()
或在之前使用 if
语句检查 null
调用方法!
关于java - 从另一个方法访问位置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269572/