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.

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"
   }
 } 
0

3 Answers 3

1

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.

Can anyone explain the reason

because onMapReady/onDataChange is/are async and not sync as you think. Android calls it their initialization, in the first case and when the new data is available in the second case. 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

Sign up to request clarification or add additional context in comments.

6 Comments

So anyway I can access that value ??
of course you can. You are already accessing it Log.d("SourceLatitude",Double.toString(value));, aren't you?
@Mr.A.N: You could send an intent when the value changes
it does show 0 on Log.d("OutsideScope",D, right ?
Yes I want to access outside scope .. and ir shows 0 there
|
0

Get yourself familiar with intents. Intents are something very basic in android applications. Here is the 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.

Comments

0

This is what you are telling the app to do:

  1. When Map is ready, add a ListenerForSingleValueEvent to srcLat and print the current value of origin_lat
  2. From now on, when data changes (onDataChange is called on that newly added listener), you want to change the value of origin_lat and print that.

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. Once that happens, origin_lat will change.

As Blackbelt says, you seem to think the code runs sequentially because it is written sequentially. Buy you added an async listener of some sort, and that will run whenever it wants.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.