com.google.firebase.database.DatabaseException:不支持序列化数组,请改用列表

fra*_*kee 14 java android firebase firebase-realtime-database

我试图使用以下代码持久化自定义对象:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference curWorkoutExercisesRef = databaseReference.child("workouts")
            .child(mCurrentWorkout.getId())
            .child("workoutExercises");

WorkoutExercise we = new WorkoutExercise(exercise);
curWorkoutExercisesRef.push().setValue(we);
Run Code Online (Sandbox Code Playgroud)

这是我的目标:

public class WorkoutExercise {

    private String id;
    private Exercise exercise;

    public WorkoutExercise() {}

    // getters, setters, other methods 
    // ...
}

public class Exercise {

    private String id;
    private String title;

    private List<BodyPart> bodyParts;

    public Exercise() {}

    // getters, setters, other methods 
    // ...
}

public class BodyPart {

    private String id;
    private String name;

    public BodyPart() {}

    // getters, setters, other methods 
    // ...
}
Run Code Online (Sandbox Code Playgroud)

每次我收到这个错误 - com.google.firebase.database.DatabaseException: Serializing Arrays is not supported, please use Lists instead.我的对象不包含任何数组,因此这个错误看起来很混乱.我找到了一种方法来修复这个错误 - 如果我将@Exclude注释添加到bodyParts我的Exercise班级列表中,一切正常,但显然不是我想要实现的.

所以似乎Firebase无法持久存在包含内部列表的对象?这里有任何简单的解决方法或最佳实践吗?谢谢!

PS我正在使用 firebase-database:9.2.1

fra*_*kee 13

我设法找到导致这次崩溃的原因.我在另一台运行Android 5.x的设备上安装了该应用,Firebase在那里引发了一个不那么令人困惑的异常:

com.google.firebase.database.DatabaseException: No properties to serialize found on class android.graphics.Paint$Align
Run Code Online (Sandbox Code Playgroud)

似乎Firebase(与Gson不同)尝试序列化所有可能的getter,即使它们没有与全局变量(类成员/字段)直接连接,在我的特定情况下,我的一个对象包含一个返回的方法Drawable- getDrawable().显然,Firebase不知道如何将drawable转换为json.

有趣的时刻(可能是Firebase SDK中的一个错误):在运行Android 4.4.1的旧设备上,我仍然在同一个项目和配置中得到原始异常:

Caused by: com.google.firebase.database.DatabaseException: Serializing Arrays is not supported, please use Lists instead
Run Code Online (Sandbox Code Playgroud)

  • 就我而言,我从可编辑字段获取数据并尝试直接推送它。将其转换为 String() 有效 (2认同)

Rba*_*bar 11

如果这可以帮助其他收到相同错误的人,则我也遇到了相同错误,并且最终的解决方案是:

变更:

databaseReference.child("somechild").setValue(etName.getText());
Run Code Online (Sandbox Code Playgroud)

至:

databaseReference.child("somechild").setValue(etName.getText().toString());
Run Code Online (Sandbox Code Playgroud)

正如@fraggjkee所指出的,Firebase尝试对getters进行序列化,这与Firebase尝试对.get的结果进行序列化的情况类似.getText()

希望这对别人有帮助!