Mithu
Mithu

Reputation: 655

Firebase Update Multiple Child value From Multiple Key for Specific Child Value

I have below firebase database Structure.I am saving mobile no as child name. What I need to do is first get the tBid value for each key having specific mobile no value equal to ok then add/deduct a number and then update tBid value for all key under b_ookk_node

enter image description here

I have tried below code so far but it is not working.How can I achieve this

final String mobile_no = singleToneClass.getInstance().getData();

mDatabasebook = FirebaseDatabase.getInstance().getReference().child("b_ookk_node");
Query ref_book = mDatabase.child(mobile_no).equalTo("ok");

ref_book.addListenerForSingleValueEvent(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        if (dataSnapshot.hasChildren()) {

            for (DataSnapshot datas: dataSnapshot.getChildren()) {

                final int total_bid = Integer.parseInt(datas.child("tBid").getValue(String.class));
                String t_bid = Integer.toString(total_bid - 1);
                mDatabasebook.child("tBid").setValue(t_bid);

            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Upvotes: 0

Views: 603

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599996

Assuming that b_ookk_node in your code matches the struck out node in your JSON screenshot, this code looks OK. But it'd require you to define an index for each mobile number, since an index can only be defined on a property of which you specify the name. Since I assume the phone numbers are user-entered data, defining an index for each of them isn't feasible

In short: your current data structure allows your to easily look up the mobile number of a push ID, but not the push ID for a mobile number. To allow the latter you'll need to set up an additional data structure, which looks like this:

"number_to_pushid_map": {
  "096554885": {
    "-LyON1kEn...sWpW": true
    "-LyON1kEn...key2": true
  }
}

In this structure you can then look up the push ID for a number that the user entered.

Also see:


Aside from that:

  • The if (dataSnapshot.hasChildren()) { in your code is not needed. If there are no child nodes, then dataSnapshot.getChildren() will already return an empty iterator, and the loop will never be entered.
  • Consider using a transaction for the updating of the bid, as right now two users updating the bid around the same time may end up overwriting each other's result.
  • Consider storing the tBid value as a number, instead of as a string, so that you don't have to constantly convert it back and forth.

Upvotes: 2

Related Questions