unity get firebase data as array code example

Example 1: how to go through child in firebase Unity

void InitializeFirebase() {


    FirebaseApp app = FirebaseApp.DefaultInstance;
    app.SetEditorDatabaseUrl ("https://slol.firebaseio.com/");

    FirebaseDatabase.DefaultInstance
        .GetReference ("Products").OrderByChild ("category").EqualTo("livingroom")
        .ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
        if (e2.DatabaseError != null) {
            Debug.LogError (e2.DatabaseError.Message);
        }


        if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0) {

            foreach (var childSnapshot in e2.Snapshot.Children) {
                var name = childSnapshot.Child ("name").Value.ToString (); 

                text.text = name.ToString();
                Debug.Log(name.ToString());
                //text.text = childSnapshot.ToString();

            }

        }

    };
}

Example 2: iterate though data in firebase unity

public void GetUsers(List<User> users)
{
        FirebaseDatabase.DefaultInstance
  .GetReference("users")
        .GetValueAsync().ContinueWith(task =>
         {
                 if (task.IsFaulted) {
      // Handle the error...
                    Debug.Log("Error was:"+task.Exception.Message);
                    Debug.LogError("Error was:"+task.Result.Children);
            }
            else if (task.IsCompleted) {
            DataSnapshot snapshot = task.Result;
            // Do something with snapshot...
                        foreach(DataSnapshot s in snapshot.Children){
                        IDictionary dictUsers = (IDictionary)s.Value;   
                        Debug.Log(dictUsers["displayName"]);                    
                    }   
                    // After this foreach loop in snapshot.Children, nothing executes
                    UIManager.instance.ShowOtherUsers();
            }
  });
}

Tags:

Go Example