I need to update the data The code is down bellow

Catalin Stoica 1 Reputation point
2021-07-05T07:08:34.607+00:00

I have to extract the data from a realtime database on firebase. I handle to extract it once with the code down bellow, but I don't know how to do manage to extract it when data on firebase is changed.

public static async Task<List<SensorsData>> GetDate()
        {
          return (await client.Child("Parking").OnceAsync<SensorsData>()).Select(item => new SensorsData{
              available = item.Object.available,
              slot1 = item.Object.slot1,
              slot2 = item.Object.slot2,
              }).ToList();

        }



        public static async Task<SensorsData> GetRomana()
        {
            try
            {
                var response = await GetDate();
                await client.Child("Parking").OnceAsync<SensorsData>();
                return response.First();
            }
            catch(Exception e)
            {
                Debug.WriteLine($"Error:{e}");
                return null;
            }

        }
Developer technologies | .NET | Xamarin
Developer technologies | C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2021-07-06T07:37:39.99+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    If you use FirebaseDatabase.net nugget package, this package do not provide any event to monitor the data change in the DB.

    Then I find the native android have ValueEventListener, So you can use this Xamarin.Firebase.Database package in xamarin android.

       public class MyValueEventListener : Java.Lang.Object, IValueEventListener  
           {  
         
               public void OnCancelled(DatabaseError error)  
               {  
                  // throw new NotImplementedException();  
               }  
         
               public void OnDataChange(DataSnapshot snapshot)  
               {  
                  // throw new NotImplementedException();  
               }  
         
           }  
    

    Then Add the data change event: DatabaseReference databaseReference = FirebaseDatabase.Instance.Reference; databaseReference.Child(Constants.ARG_CHAT_ROOMS).Ref.AddListenerForSingleValueEvent(new MyValueEventListener())

    Here is an similar thread:

    https://stackoverflow.com/questions/42499066/how-to-use-interface-ivalueeventlistener-in-object-databasereference-xamarin-fir

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.