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 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Passing json to firebase is the preferred way to communicate with firebase. Design according to it.
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?
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.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.