0

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);
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you so much. I getting the logic now. But why I cant do this inside of ondatachange? id.Text = recList[0].ID; its says not an instance of an object. – Don Min Soo Dec 09 '21 at 00:45
  • I'm not sure why that is, but I recommend checking in the debugger (as one of the objects seems to not have been initialized) and search for the error message. – Frank van Puffelen Dec 09 '21 at 01:18
  • Can I call the textview Id in onDataChange()? – Don Min Soo Dec 09 '21 at 01:31
  • Yes, you can. But in your code it seems `id` is not initialized. I recommend learning how to troubleshoot by looking at the [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) post that was linked to [your follow-up question you deleted](https://stackoverflow.com/questions/70283509/please-help-im-getting-an-error-in-id-text-why-im-getting-a-null-id-is-there-a). – Frank van Puffelen Dec 09 '21 at 02:11