【发布时间】:2019-11-27 07:28:06
【问题描述】:
我有一个模型,其中包含字段 1- 名称、2- 价格,
一个 firebase 函数获取项目列表(包含两个字段)
然后我有一个将数据添加到 firebase 的按钮。添加名字然后添加价格
public void addItemForStore(String itemName, String itemPrice) {
DatabaseReference ref = database.getReference().child("items").push();
ref.child("name").setValue(itemName);
ref.child("price").setValue(itemPrice);
}
但问题是当添加名称时
public void getStoreItemData(final StoreItemCallBack callBack) {
DatabaseReference ref = database.getReference().child("items");
final ArrayList<StoreItemModel> list = new ArrayList<>();
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
list.clear();
for(DataSnapshot item : dataSnapshot.getChildren()){
String key = item.getKey();
list.add(new StoreItemModel(key, item.child("name").getValue().toString(),
item.child("price").getValue().toString()));
}
callBack.onSuccess(list);
}else{
callBack.onSuccess(null);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callBack.onFailure(databaseError.toException());
}
});
}
上述函数的onDataChange被触发,它将price的值设为null并崩溃应用程序。
下次我重新启动应用程序时,它会正确显示,因为现在数据已添加。
更新 显示错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
数据库 -
【问题讨论】:
-
如果应用程序崩溃,会有一个堆栈跟踪。请在 logcat 上查找,并将其添加到您的问题中。还请将您的数据库结构添加为 JSON 文件或至少是屏幕截图。
-
这条声明
item.child("price").getValue().toString()使您的应用程序崩溃?
标签: java android firebase firebase-realtime-database