Firebase Android count children/ badge

前端 未结 2 740
情歌与酒
情歌与酒 2020-12-15 12:21

I try to develop a simple shopping application. There will be a few product categories and I use different activity with ListView for every category. When User choose produc

相关标签:
2条回答
  • 2020-12-15 12:36

    I'm not sure about that but It can couse of parsing. Try to

    badgeView.setText(nums+"");
    

    maybe It could help.

    0 讨论(0)
  • 2020-12-15 12:58

    With this Database you have two options:

    1)Use Child Added

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference();
    //You must remember to remove the listener when you finish using it, also to keep track of changes you can use the ChildChange
    myRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Log.e(dataSnapshot.getKey(),dataSnapshot.getChildrenCount() + "");
        }
    
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    
        }
    
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
    
        }
    
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
    
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
    
        }
    });
    

    2)Use the Value listener

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference();
    
    //You can use the single or the value.. depending if you want to keep track
    thismyRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snap: dataSnapshot.getChildren()) {
                Log.e(snap.getKey(),snap.getChildrenCount() + "");
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
    
        }
    });
    

    Here is the output for both cases

    If you need to keep constant tracking is best to use the Child events...because otherwise each time anything changes you will receive the entire json over the network, instead of only the portion of information that was changed

    If you need a snapshot only once, you better use the singleValue since this way you will receive all the information at the same time

    0 讨论(0)
提交回复
热议问题