Daniel Calderon Daniel Calderon - 1 year ago 97
Android Question

Ondatachanged not saving variable values once done

My issue is that when the onDataChange function runs it does not save the values added to events. The events list does exist within the onDataChange but once i try to access the values out side of it, it longer has them. I am not too sure how to fix this.

public void saveNewEvent(String uid, String eventId, String eventName, String eventHost,String eventTime, String eventAddress, String eventImage, String eventDescription) {
savedEventsCreated = false;
events.clear();

UserEvents info = new UserEvents(eventName, eventHost, eventTime, eventAddress, eventId, eventImage, eventDescription);
savedEvents.child("savedEvents").child(eventId).setValue(info);
users.child(uid).child("eventsList").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
events.add(postSnapshot.getValue().toString());
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

for (int i = 0; i < events.size(); i++)
Log.i("Info", events.get(i));
events.add(eventId);
users.child(uid).child("eventsList").setValue(events, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
System.out.println("Data could not be saved " + databaseError.getMessage());
} else {
System.out.println("Data saved successfully.");
}
}
});
}

Answer Source

This happening because your events list is not defined inside the onDataChange() method. To solve this, move the declaration of that list inside onDataChange() method, otherwise it will be null. This is happening due the asynchronous behaviour of that method which is called before even you add those values to the list.

If you want to use those values outside the onDataChange() method, please see my answer from this post.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download