L
L
LilSem2017-05-27 16:04:45
Java
LilSem, 2017-05-27 16:04:45

How to fix app crash when adding data to Firebase?

I have two fragments, one of them is a basket and there is an AddChildEventListener on it, that is, it constantly listens to the state of the database and when adding data to the basket, that is, from the second fragment, the basket fragment immediately tries to update the list, and because of this time, only two fields manage to come to the database, instead of eight, the listener cannot load non-existent data and the application crashes. How to solve this issue? Listings below
Adding to the database:

String key = mReference.child("basket").push().getKey();
    mReference.child("basket").child(key).child("dishId").setValue(mList.get(position).id);
    mReference.child("basket").child(key).child("restaurantId").setValue(mList.get(position).restaurantId);
    mReference.child("basket").child(key).child("userId").setValue(userRef);
    mReference.child("basket").child(key).child("weight").setValue(mList.get(position).weight);
    mReference.child("basket").child(key).child("title").setValue(mList.get(position).title);
    mReference.child("basket").child(key).child("composition").setValue(mList.get(position).composition);
    mReference.child("basket").child(key).child("price").setValue(mList.get(position).price);

Listener:
private void updateList() {

    mReference.child("basket").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            mList.add(dataSnapshot.getValue(Basket.class));
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            Basket model = dataSnapshot.getValue(Basket.class);
            int index = getItemIndex(model);
            mList.set(index, model);
            mAdapter.notifyItemChanged(index);

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            Basket model = dataSnapshot.getValue(Basket.class);
            int index = getItemIndex(model);

            mList.remove(index);
            mAdapter.notifyItemRemoved(index);
        }


        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question