从Firebase实时数据库读取数据时遭遇类型转换错误
Firebase实时数据库数据类型转换错误解决方法
报错信息
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
问题原因
- 类型不匹配:模型类
Cartmodel中totalPrice定义为int类型,但Firebase数据库里对应的totalPrice是字符串类型(如示例中的"1750.0"),Firebase无法自动完成字符串到int的转换,因此抛出错误。 - 写入逻辑混乱:新增商品时
cartMap.put("totalPrice",result)存入的是double类型,但更新商品时却通过String.valueOf(newTotalPrice)存成了字符串,导致数据库中totalPrice类型不一致。
解决方案
1. 统一模型类与数据库的类型
修改Cartmodel的totalPrice为double类型(适配可能存在的小数总价),并补全对应的getter方法:
public class Cartmodel { private String date; private String productImage; private String productName; private String productPrice; private String quantity; private String time; private double totalPrice; // 改为double类型 public Cartmodel() { // Default constructor required for calls to DataSnapshot.getValue(Cartmodel.class) } public Cartmodel(String date, String productImage, String productName, String productPrice, String quantity, String time, double totalPrice) { this.date = date; this.productImage = productImage; this.productName = productName; this.productPrice = productPrice; this.quantity = quantity; this.time = time; this.totalPrice = totalPrice; } // 补全totalPrice的getter方法 public double getTotalPrice() { return totalPrice; } // 其他原有getter/setter方法保持不变 public String getProductImage() { return productImage; } public void setProductImage(String productImage) { this.productImage = productImage; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductPrice() { String price = this.productPrice.replace("₹", ""); return price; } public void setProductPrice(String productPrice) { this.productPrice = productPrice; } public String getQuantity() { return quantity; } public void setQuantity(String quantity) { this.quantity = quantity; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } }
2. 统一写入数据的类型
确保新增和更新商品时,totalPrice都存入数字类型而非字符串:
- 新增商品逻辑保持不变(原本存入的是
double类型) - 修改更新商品的代码,直接传入
newTotalPrice(double类型):
// 替换原更新totalPrice的代码 cartListRef.child(currentUserPhoneNumber).child(cartKey).child("totalPrice").setValue(newTotalPrice);
3. 清理数据库错误数据
手动在Firebase控制台中将现有字符串类型的totalPrice(如"1750.0")修改为数字类型1750.0,避免读取旧数据时仍出现转换错误。
4. 适配适配器中的显示逻辑
在cartAdapter的onBindViewHolder方法中,将double类型的totalPrice转为字符串显示:
holder.totalprice.setText("Total: ₹" + String.valueOf(cartmodel.getTotalPrice())); // 如需保留两位小数,可改为: // holder.totalprice.setText("Total: ₹" + String.format("%.2f", cartmodel.getTotalPrice()));
内容的提问来源于stack exchange,提问作者Aditya Singh Rajput
相关产品推荐
相关产品推荐

