How to sum older data with new one in firebase

守給你的承諾、 提交于 2021-02-10 14:49:18

问题


I have table named poin and kegiatan, when I input score to kegiatan, its input to poin too, the problem is when I input score to poin and sum it with older data in poin, its will looping over and over. what should I do? Btw, this is how my database and code for input score to poin look like.

kegiatan + user id - poin = score poin +stringDate -userId = score

reference = FirebaseDatabase.getInstance().getReference();
reference.child("poin").child(stringdate).child(nama).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        Integer previousScore = dataSnapshot.getValue(Integer.class);
        if (previousScore != null){
            Integer nita = previousScore + 2;
            dataSnapshot.getRef().setValue(nita);
        }else {
            dataSnapshot.getRef().setValue(0);
        }

        Toast.makeText(getActivity(),"Jumlah : "+nita, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

and I use date as child, how can I add new child everyday? thanks for advance


回答1:


I would suggest you store all points (poin) and total them up. Example database you can change something like this.

 -poin
  -stringDate
   -userId
     -poinUid1
       -score : 100
     -poinUid2
       -score : 200


so code like this. you get the total sum of poin. I changed addListenerForSingleValueEvent if you want to read the data once but if you have data which is NEED to read always, you need to use addValueEventListener.

//Get all the sums and display. 
FirebaseDatabase.getInstance().getReference().child("poin").child(stringdate).child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            long sum = 0;
            for (DataSnapshot snapShot : dataSnapshot.getChildren()) {
                if (snapShot.exists()) {
                    long size = snapShot.child("score").getValue(Long.class);
                    sum += size;
                    textViewTotal.setText(String.valueOf(sum));

                }

            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});


来源:https://stackoverflow.com/questions/59942308/how-to-sum-older-data-with-new-one-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!