Home > Enterprise >  How to parse data from the firebase database to int
How to parse data from the firebase database to int

Time:12-12

public void saveData()
{
    Reference.Child("users").Child(userId).Child("level").SetValueAsync(levelText.text.ToString());
}

public void loadData()
{
    FirebaseDatabase.DefaultInstance.GetReference("").ValueChanged  = Script_ValueChanged;
}

private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
    levelText.text = e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true).ToString();
}

In this example I can load my level from the database and save it. My problem right now is I want to load the level from the database and store it in a Int level Variable so I can make a levelup function and update the level in the database. Does someone know how to do that?

private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
    level = (int)e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true);
    levelText.text = level.ToString();
}

my idea was maybe doing it in that way, but inside unity It gives me an error message at that line: "System.InvalidCastException: Specified cast is not valid."

CodePudding user response:

You need to parse the int from the string, because a string cannot be cast to an int. You can use int.Parse() for that if you know that it contains a valid integer:

private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
    level = int.Parse(e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true));
    levelText.text = level.ToString();
}

Documentation for int.Parse(): https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-7.0

Alternatively, you can also use int.TryParse() if you're not 100% certain that the string contains a valid integer:

private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{ 
    if(int.TryParse(e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true), out int parsedInt))
    {
        level = parsedInt;
    }
    levelText.text = level.ToString();
}

Documentation for int.TryParse(): https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-7.0

Another solution would be to use Convert.ToInt32() instead of int.Parse(), but it will do the same thing: https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=net-7.0

  • Related