Gilad Neiger
Gilad Neiger

Reputation: 319

Can't affect declared variable

I'm trying to make a method which returns int variable, but the method doesn't effect the variable.

This is my code:

int count;
public int getVotesForEvent(final String event_title) {
    firebaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.child("Votes").exists()) {
                boolean flag = false;
                for (DataSnapshot event : dataSnapshot.child("Votes").getChildren()) {
                    String event_title2 = event.getKey();
                    if (event_title2.equals(event_title)) {
                        flag = true;
                        Toast.makeText(EventInfo.this, ""+Integer.parseInt(event.child("event_votes").getValue().toString()), Toast.LENGTH_SHORT).show();
                        count = Integer.parseInt(event.child("event_votes").getValue().toString());
                    }
                }
                if (flag != true) {
                    count = 0;
                }
            }
            else {
                count = 0;
            }
        }
    });
    return count;
}

The problem is that the line:

count = Integer.parseInt(event.child("event_votes").getValue().toString());

This line is not effecting the variable count.

What am I doing wrong here?

Upvotes: 0

Views: 101

Answers (1)

Honza Zidek
Honza Zidek

Reputation: 20166

The method getVotesForEvent() itself does not call the code inside. So the value of count is not changed as your code returns from getVotesForEvent().

The methods only adds a ValueEventListener (as its name suggest :) ) with the defined behavior.

Only after an onDataChange event occurs, the code inside is performed.

There is no sense in returning count from getVotesForEvent(), it will just return the value which was there at the time you called that method, not when the value of count changes (sometimes in the future).

To repeat in other words: when calling addValueEventListener(), you are not executing the code it contains. You are only "loading" the code to be executed later, whenever the respective event occurs.

Think about your code as this:

int count;
public int getVotesForEvent(final String event_title) {
    firebaseRef.addValueEventListener(what-shall-be-done-sometimes-in-the-future-when-onDataChange-event-occurs);
    return count;
}

and here you clearly see that the value of count is not changed.

Upvotes: 1

Related Questions