Daniel Calderon Daniel Calderon - 3 years ago 121
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;

UserEvents info = new UserEvents(eventName, eventHost, eventTime, eventAddress, eventId, eventImage, eventDescription);
users.child(uid).child("eventsList").addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

public void onCancelled(DatabaseError databaseError) {


for (int i = 0; i < events.size(); i++)
Log.i("Info", events.get(i));
users.child(uid).child("eventsList").setValue(events, new DatabaseReference.CompletionListener() {
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