locked
How to handle Firebase Database callbacks? RRS feed

  • Question

  • User308154 posted

    I'm trying to use the Xamarin.Firebase.Database plugin. This is was I have:

    ``` DatabaseReference firebaseDb; ... firebaseDb.Child(DATABASE).AddListenerForSingleValueEvent(new ReadListener(this)); ... class ReadListener : Java.Lang.Object, IValueEventListener { FirebaseManager mFirebaseManager;

        public ReadListener(FirebaseManager manager)
        {
            mFirebaseManager = manager;
        }
    
        public void OnCancelled(DatabaseError error)
        {
            Debug.WriteLine("ERROR: " + error, "LOADDATA");
        }
    
        public void OnDataChange(DataSnapshot snapshot)
        {
            if (snapshot == null) return;
    
            var snapChildren = snapshot.Children;
            var iterator = snapChildren.Iterator();
            var items = new List<DataItem>();
    
            while (iterator.HasNext)
            {
                var item = iterator.Next();
                // item is a Java.Lang.Object, so how can I change it to DataItem?
                // I've tried to create a DataItemJava : Java.Lang.Object, 
                // and have var item = (DataItemJava) iterator.Next();
                // but I get a System.InvalidCastException
            }
    
        }
    }
    

    ```

    So my answer is, how to get from snapshot.Children to IList<DataItem>?

    Tuesday, March 21, 2017 11:05 AM

All replies

  • User203076 posted

    Try this...

    public void OnDataChange(DataSnapshot snapshot)
    {
        if (snapshot == null) return;
        var snapChildren = snapshot.Children;
        foreach(DataSnapshot snapshot in snapChildren.ToEnumerable())
        {
            IList<CustomClass> obj = new List<CustomClass>();
    
            if (snapshot.GetValue(true) == null) continue;
    
            obj.PropertyName1 = snapshot.Child("attribute_name_1").GetValue(true).ToString();
            obj.PropertyName2 = snapshot.Child("attribute_name_2").GetValue(true).ToString();
            obj.PropertyName3 = snapshot.Child("attribute_name_3").GetValue(true).ToString();
        }
    }
    
    // CustomClass, PropertyName, attibute_name are all to be substituted per your data model.
    
    Tuesday, May 30, 2017 1:18 PM