[英]Accessing Variable inside Inner Class
I have a listener and I want to access variable outside the listener method. 我有一个侦听器,我想在侦听器方法之外访问变量。 But even after initializing the variable globally its showing "0" outside scope.
但是,即使在全局初始化变量后,它在范围外仍显示“ 0”。
Can anyone explain the reason 谁能解释原因
public class MapsActivity{
double origin_lat;
//
@Override
public void onMapReady(GoogleMap googleMap) {
//
srcLat.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
double value = (double) dataSnapshot.getValue();
origin_lat=value; -- > value shows here
Log.d("SourceLatitude",Double.toString(value));
}
});
Log.d("OutsideScope",Double.toString(origin_lat)); -- > shows "0"
}
}
I have a listener and I want to access variable outside the listener method.
我有一个侦听器,我想在侦听器方法之外访问变量。 But even after initializing the variable globally its showing "0" outside scope.
但是,即使在全局初始化变量后,它在范围外仍显示“ 0”。
Can anyone explain the reason
谁能解释原因
because onMapReady/onDataChange
is/are async
and not sync
as you think. 因为
onMapReady/onDataChange
是async
而不是您认为的sync
。 Android calls it their initialization, in the first case and when the new data is available in the second case. 在第一种情况下,Android将其称为初始化,在第二种情况下,则可使用新数据。 The purpose of having them async is to avoid to block the UI Thread in case of heavy computation, leaving your users the possibility to interact with the UI
使它们异步的目的是避免在计算量大的情况下阻塞UI线程,从而使用户可以与UI进行交互
Get yourself familiar with intents. 让自己熟悉意图。 Intents are something very basic in android applications.
意图是android应用程序中非常基本的东西。 Here is the docu: Android Docu
这是文档: Android Docu
You would then send an intent to your activity. 然后,您将向您的活动发送意图。 In the activity you woul register a receiver, that uses the value of the intent.
在活动中,您将注册一个使用意图值的接收器。
This is what you are telling the app to do: 这是您要告诉应用程序执行的操作:
ListenerForSingleValueEvent
to srcLat
and print the current value of origin_lat
ListenerForSingleValueEvent
到srcLat
和打印的当前值origin_lat
onDataChange
is called on that newly added listener), you want to change the value of origin_lat
and print that. onDataChange
)时,您想要更改origin_lat
的值并进行打印。 Note that in step 1, the value of origin_lat
has not (necessarily) yet been modified by onDataChange
because onDataChange
has not been called yet. 请注意,在第1步中,
origin_lat
尚未(必需)修改onDataChange
因为尚未调用onDataChange
。 Once that happens, origin_lat
will change. 一旦发生这种情况,
origin_lat
将更改。
As Blackbelt says, you seem to think the code runs sequentially because it is written sequentially. 正如Blackbelt所说,您似乎认为代码是按顺序运行的,因为它是按顺序编写的。 Buy you added an async listener of some sort, and that will run whenever it wants.
购买后,您添加了某种异步侦听器,该侦听器将在需要时运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.