问题描述
我有一个名为poin和kegiatan的表,当我向kegiatan输入得分时,也将其输入为poin,问题是当我输入score到poin并将其与poin中的旧数据求和时,它会反复循环.我应该怎么办?顺便说一句,这就是我的数据库和用于输入乐谱的代码.
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+用户ID-点=分数in+ stringDate-userId =得分
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) {
}
});
我将date作为孩子,我如何每天添加新孩子?谢谢你的进步
and I use date as child, how can I add new child everyday? thanks for advance
推荐答案
我建议您存储所有点(点)并进行总计.示例数据库,您可以更改类似的内容.
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
所以这样的代码.您会得到一磅钱的总和.如果您想一次读取数据,但我更改了 addListenerForSingleValueEvent
,但是如果需要始终读取的数据,则需要使用 addValueEventListener
.
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) {
}
});
这篇关于如何在Firebase中将旧数据与新数据相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!