Android Firebase获取子节点值问题:Receipt对象返回null
Hey there! Let's walk through why your Receipt instance is coming up null when fetching data, and how to fix it. These are the most common culprits:
1. Mismatched Field Names (Most Likely)
Firebase relies on exact name matching when serializing/deserializing objects. If your Receipt class has fields named differently than the keys in your database (e.g., orderId in the DB vs order_id in your class), the mapping will fail silently, resulting in a null object.
Fix:
Either rename your class fields to match the database keys exactly, or use the @PropertyName annotation to explicitly link them:
import com.google.firebase.database.PropertyName; public class Receipt { @PropertyName("order_id") // Match the key in your database private String orderId; // Don't forget to annotate getters/setters too @PropertyName("order_id") public String getOrderId() { return orderId; } @PropertyName("order_id") public void setOrderId(String orderId) { this.orderId = orderId; } }
2. Missing No-Argument Constructor
Firebase requires a public no-argument constructor to instantiate your Receipt class. If you only have constructors with parameters, Firebase can't create an instance of the class, leading to null.
Fix:
Add an empty constructor to your Receipt class:
public class Receipt { // Required for Firebase deserialization public Receipt() {} // Your existing parameterized constructors, fields, etc. }
3. Inaccessible Fields or Missing Getters/Setters
Firebase needs to access your class's fields to populate them. If fields are private and you don't have corresponding getter/setter methods, Firebase can't assign values to them.
Fix:
Either make your fields public, or add standard getter and setter methods for every field you want to map from the database.
4. Data Type Mismatch
If a field in your Receipt class has a different data type than the corresponding value in Firebase (e.g., a String in your class vs an integer in the DB), the mapping will fail.
Fix:
Double-check the data types of each key in your database and ensure they match the fields in your Receipt class exactly.
5. Incorrect Database Path
Double-confirm that the path shop/orders is pointing directly to the parent node of your red-region data. If the red region is nested deeper (e.g., shop/orders/{someId}/receipt), your current code isn't targeting the right node.
Debug Tip:
Add a print statement to see the raw data you're fetching—this will help you confirm if the issue is with the path or the object mapping:
@Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { for (DataSnapshot temp : dataSnapshot.getChildren()) { // Print raw data to verify System.out.println("Fetched raw data: " + temp.getValue().toString()); Receipt temp2 = temp.getValue(Receipt.class); } } }
内容的提问来源于stack exchange,提问作者Hoàng Thái

