0

I am trying to store an Int32[] Array and bool[] Array to Firebase but it isn't working for me. I have searched on various places, but couldn't find a solution. Can anyone tell me, how one can store an array to Firebase Real-time DB from Unity.

I am using System.Reflection to get all the public static fields of the class UserPrefs.

Here is the code, I am trying to do this job...

        System.Type type = typeof(UserPrefs);
        FieldInfo[] fields = type.GetFields();
        foreach (var field in fields) {
            if (user != null)    
        dbReference.Child("users").Child(user.UserId).Child(field.Name).SetValueAsync(field.GetValue(null));
            else
                    Debug.LogError("There is no user LoggedIn to write...");
        }

Above code saves all values other than arrays. Error given on arrays is following:

InvalidCastException: Cannot cast from source type to destination type. Firebase.Database.Internal.Utilities.Validation.ValidateWritableObject (System.Object object)

Any help will be much appreciated...

2 Answers2

1

You need a class like this.

public class MyClass
{
    public int[] intArray = new int[10];
}

Then you can write that object to the Firebase like this.

public void WriteArrays()
{
    MyClass temp = new MyClass();

    for (int i = 0; i < temp.intArray.Length; i++)
    {
        temp.intArray[i] = i;
    }

    databaseReference.Child("MyArrayNode").SetRawJsonValueAsync(JsonUtility.ToJson(temp));
}

databaseReference is a reference to your root.

Same way you can do this for your bool[] also.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bhavin Panara
  • 428
  • 4
  • 11
  • There can be many other arrays of other types. I need to make the code generic. It's not a good solution to make class for all possible arrays, iterate in a loop and then save to Firebase. All this will be done again while loading the data. – Farhan Shehzad Nov 06 '18 at 10:34
  • Passing json to firebase is the preferred way to communicate with firebase. Design according to it. – Bhavin Panara Nov 06 '18 at 10:49
  • So, you are saying I need to design my own json object, in case I want to save arrays to Firebase. If so, can you please give me any example code to make a json for arrays? – Farhan Shehzad Nov 06 '18 at 12:52
  • I am saying that whenever you want to pass more than one thing to Firebase, use json. You can use in-built json utility of Unity. – Bhavin Panara Nov 14 '18 at 04:26
0

For a more general solution you can copy the JsonHelper class which was suggested here.

Example usage:

string jsonArray = JsonHelper.ToJsonArray(mySerializeableList);
var nodeToUpdate = this.dbReference.Child("wantedNode");
nodeToUpdate.SetRawJsonValueAsync(jsonArray);
eladleb
  • 2,616
  • 26
  • 21