【问题标题】:Wait for onDataChange in Firebase在 Firebase 中等待 onDataChange
【发布时间】: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


【解决方案1】:

您现在通过两个单独的调用将这两个值设置到数据库中:

DatabaseReference ref = database.getReference().child("items").push();
ref.child("name").setValue(itemName);
ref.child("price").setValue(itemPrice);

这会导致您的onDataChange 被调用两次。您可以通过检查 null 来解决 onDataChange 中的问题。

但更好的方法可能是在一次调用中添加名称和价格:

DatabaseReference ref = database.getReference().child("items").push();
Map<String, Object> values = new HashMap<>();
values.put("name", itemName);
values.put("price", itemPrice);
ref.setValue(values);

现在只有一个写入操作,所以您的 onDataChange 会得到它期望的两个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2017-09-13
    相关资源
    最近更新 更多