我想从Firebase读取数据以增加数据并写回Firebase。这是我的功能:
StatData = FirebaseDatabase.getInstance().getReference("Statistic");
Getstat = FirebaseDatabase.getInstance().getReference("Statistic");
Getstat.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Stat stat = dataSnapshot.getValue(Stat.class);
int count = stat.getStatP();
int statP = count + 1;
Stat a = new Stat(statP);
StatData.setValue(a);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
我正在使用同一类Stat来读写数据。可以使用吗?
答案 0 :(得分:1)
基于该节点的当前值use a Firebase transaction将值写入该节点。您的示例如下所示:
postRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Stat stat = mutableData.getValue(Stat.class);
if (stat == null) {
// Node doesn't exist or its value isn't known yet => return success
return Transaction.success(mutableData);
}
int count = stat.getStatP();
int statP = count + 1;
stat = new Stat(statP);
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "statTransaction:onComplete:" + databaseError);
}
});