Android Studio中Firebase实时数据库CRUD崩溃:User类无参构造缺失解决方案
First, let's highlight the key error from your logcat that points to the root issue:
com.google.firebase.database.DatabaseException: Class studenty.language.android.User does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
Firebase Realtime Database relies on a no-argument (default) constructor to create instances of your custom objects when pulling data from the database. Your current User class only has parameterized constructors, which is why the crash occurs when Firebase tries to deserialize data.
How to Add the Required No-Argument Constructor
Adding this constructor is simple—just insert a constructor with no parameters into your User class. It can be empty (Firebase only needs it to instantiate the object, then uses your setter methods to populate fields).
Here's your updated User class with the missing constructor:
package studenty.language.android; public class User { private String id; private String name; // Required no-argument constructor for Firebase public User() { // Empty body is totally fine here } public User(String id) { this.id = id; } public User(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Why This Fixes the Crash
When Firebase retrieves data from the database, it first creates an empty User instance using the no-argument constructor. Then it uses your public setter methods (setId(), setName()) to fill in the data from the database. Without this constructor, Firebase can't create the object at all, leading to the exception you saw.
If you're using ProGuard in your project, make sure you don't accidentally strip this constructor during obfuscation. Add these rules to your ProGuard config to keep the User class and its constructors intact:
-keep class studenty.language.android.User { public <init>(); public <init>(java.lang.String); public <init>(java.lang.String, java.lang.String); public void setId(java.lang.String); public void setName(java.lang.String); }
内容的提问来源于stack exchange,提问作者Rene

