Manmohan Gupta
Manmohan Gupta

Reputation: 35

Wait for onDataChange in Firebase

I have a model that contains fields 1- name , 2- price,

One firebase function gets the list of items (with both the fields)

Then i have a button that adds the data to firebase. first name is added then price is added

public void addItemForStore(String itemName, String itemPrice) {
    DatabaseReference ref = database.getReference().child("items").push();
    ref.child("name").setValue(itemName);
    ref.child("price").setValue(itemPrice);
}

but the problem is that when name is added then

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 of above function is triggered and it gets the value of price as null and crashes the app.

the next time when i relaunch the app its shows it properly because now the data has been added.

UPDATE error shown :

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

Database -

enter image description here

Upvotes: 0

Views: 250

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600131

You're now setting the two values into the database with two separate calls:

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

This leads to your onDataChange being called twice. You could fix the problem in onDataChange, by checking for null.

But a better way is probably to add name and price in a single call:

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

Now there's only a single write operation, so your onDataChange gets both values it expects.

Upvotes: 1

Related Questions