I'm trying to get data from db. But problem is Datasnapshot result is not correct. Result children are has an extra element which is last element in db. Can you say what I'm doing wrong?
Unity3D version: 2019.2.18f1 Firebase version: 8.6.1
Data:
"0" : {
"deskID" : 0,
"deskName" : "Sol iç 1"
},
"1" : {
"deskID" : 1,
"deskName" : "Sol iç 2"
},
"2" : {
"deskID" : 2,
"deskName" : "Sol iç 3"
},
"3" : {
"deskID" : 3,
"deskName" : "Sağ iç 1"
},
"4" : {
"deskID" : 4,
"deskName" : "Sağ iç 2"
},
"5" : {
"deskID" : 5,
"deskName" : "Sağ iç 3"
},
"6" : {
"deskID" : 6,
"deskName" : "Sol dış 1"
},
"7" : {
"deskID" : 7,
"deskName" : "Sol dış 2"
},
"8" : {
"deskID" : 8,
"deskName" : "Sağ dış 1"
},
"9" : {
"deskID" : 9,
"deskName" : "Sağ dış 2"
},
"10" : {
"deskID" : 10,
"deskName" : "Sağ dış 3"
},
"11" : {
"deskID" : 11,
"deskName" : "Sağ dış 4"
},
"12" : {
"deskID" : 12,
"deskName" : "Sağ dış 5"
},
"13" : {
"deskID" : 13,
"deskName" : "Sağ dış 6"
},
"9999" : {
"deskID" : 9999,
"deskName" : "Personel"
}
},
Function to use get data:
FirebaseDatabase.DefaultInstance.GetReference("desks").GetValueAsync().ContinueWithOnMainThread((task) =>
{
Desks desks = new Desks();
if (task.IsFaulted)
{
Debug.Log("error read desk data");
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
Debug.Log(snapshot.ChildrenCount);
if (snapshot.ChildrenCount > 0)
{
foreach (DataSnapshot snapshotChild in snapshot.Children)
{
try
{
Desk desk = JsonUtility.FromJson<Desk>(snapshotChild.GetRawJsonValue());
Debug.Log(desk.deskName);
desks.desks.Add(desk);
}catch(Exception ex)
{
Debug.Log(snapshotChild.Key);
Debug.Log(snapshotChild.Value);
Debug.Log(ex.Data);
Debug.Log(ex.Message);
}
}
}
And here is the log data. As you see last element was "9999" -> deskID = 9999, deskName = "Personel". But in the log as you can see last elements deskID and deskName shown as snapshot child in result.
Edit:
First I want to explain more what's the wrong with result data. My result list has to be 15 children. But sometimes result get 17 children. 16th child's Key: 'deskID' and Value: '9999' and 17th child's Key: 'deskName' and Value: 'Personel'.
Desk class:
[Serializable]
public class Desk
{
public int deskID;
public string deskName;
}
After Frank van Puffelen's answer this error is gone. I tried 30 times and get exact data from database.
CodePudding user response:
Most likely you are seeing the results of Firebase's array-coercion. When you retrieve data whose keys look like array indices, the Firebase SDKs and REST API convert the results to an array. If a few of the keys in the array are missing, those get filled with null
values.
To prevent this from happening, don't use sequential numeric values for your keys. Instead either use Firebase's native push keys, or give your numeric keys a short string prefix to prevent the array coercion, i.e. key_0
, key_1
, etc.
For more on this, see Best Practices: Arrays in Firebase.