Transaction causing activity to recall Firebase Android

前端 未结 1 1686
生来不讨喜
生来不讨喜 2020-12-19 17:29

When I click my rate_btn to start this transaction function.

It works fine but in the process it re-run my class activity one more time (my class a

相关标签:
1条回答
  • 2020-12-19 18:06

    Since the Message ID changes every every time transaction is called, this is because of addValueEventListener (it accept the changes when calling transaction). Therefore to solve this I add addListenerForSingleValueEvent instead of addValueEventListener and it worked.

    For Example:

     ref.addListenerForSingleValueEvent(new ValueEventListener() {
    
        public void onDataChange(DataSnapshot snapshot) {
            Iterable<DataSnapshot> ds = snapshot.getChildren();
    
            //getting maximum number of children
            long allNum = snapshot.getChildrenCount();
            int maxNum = (int)allNum;
    
            //getting the random integer from number of children
            int randomNum = new Random().nextInt(maxNum);
    
            Iterator<DataSnapshot> ids = ds.iterator();
    
            int count = 0;
    
            //has next will check if there are values in the next iteration , while count is used as a position substitute.
            while(ids.hasNext() && count < randomNum) {
                ids.next();
                count ++; // used as positioning.
            }           
    
            Map<String, Object> newPost = (Map<String, Object>) ids.next().getValue(); // ids will take the value in the iterator (iterate at key) 
            //getting the message from the key
            msgID = newPost.get("id").toString();
        }`
    
    0 讨论(0)
提交回复
热议问题