Search code examples
c#firebase-realtime-databasexamarin.android

Firebase Realtime Database Retrieved Single Data on Xamarin Android


I successfully get the data from realtime database firebase when I put break point on OndataChange but when I put the break point after the OnDataChange method the records are now null.

public void OnDataChange(DataSnapshot dataSnapshot)
{
   
    if (dataSnapshot.Value != null)
    {
        reclist.Clear();
        TempDB rec = new TempDB();


        rec.ID = dataSnapshot.Key;
        rec.Firstname = dataSnapshot.Child("FirstName").Value.ToString();
        rec.Lastname = dataSnapshot.Child("LastName").Value.ToString();
        rec.Address = dataSnapshot.Child("Address").Value.ToString();
        rec.ContactNo = dataSnapshot.Child("Contact number").Value.ToString();
        rec.Email = dataSnapshot.Child("EmailAddress").Value.ToString();
        rec.Password = dataSnapshot.Child("Password").Value.ToString();

        idd = rec.ID;
        Console.WriteLine(id.ToString());
        reclist.Add(rec);
    }
}

Solution

  • That's because data is loaded from Firebase asynchronously, while the rest of your code continues. Then once the data is loaded, your onDataChange is called with it. This means that the code just after what you shared indeed runs before the code inside the onDataChange, and that is working as intended.

    The solution is always the same: any code that needs the data from the database needs to be inside onDataChange, be called from there, or be otherwise synchronized.

    Have a look at these two (Android) examples for some ideas: