英文:
Trying to update Database addValueEventListener
问题
public void savePractice(){
// 这个方法将练习保存到运动员的数据库中
currentAthleteRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
currentAthlete = dataSnapshot.getValue(Athlete.class);
if (currentAthlete.practices == null){
currentAthlete.practices = new ArrayList<Practice>();
currentAthlete.practices.add(practice);
}
else {
currentAthlete.practices.add(practice);
}
currentAthleteRef.child("Practices").setValue(currentAthlete.practices);
finish();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
showProgress("无法找到运动员,请告诉我们!!!!");
}
});
}
英文:
I am trying to update my database.
Something that i am doing doesn’t work. At the first time that I call this method it updates the database but finishes the activity. At the second time that I call that method it gets into an infinite loop.
public void savePractice(){
//This Method saves the Practice in the Database under the Athlete practices
currentAthleteRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
currentAthlete = dataSnapshot.getValue(Athlete.class);
if (currentAthlete.practices == null){
currentAthlete.practices = new ArrayList<Practice>();
currentAthlete.practices.add(practice);
}
else {
currentAthlete.practices.add(practice);
}
currentAthleteRef.child("Practices").setValue(currentAthlete.practices);
finish();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
showProgress("Failed to find Athlete please tell us!!!!!!");
}
});
}
答案1
得分: 0
我快速的猜测是你想要仅一次读取数据,然后进行更新。然而,这并不是你的代码所做的:addValueEventListener
添加了一个半永久的监听器,会持续活跃地监听数据,直到你移除它。
如果你想仅仅读取一次数值,然后停止监听变化,你应该使用:
currentAthleteRef.addListenerForSingleValueEvent(...
总的来说:如果新值依赖于同一数据库位置的当前值,你应该使用事务来防止并发更新相互覆盖。
英文:
My quick guess is that you're looking to read the data only once, and update it. That is not what your code does however: addValueEventListener
adds a semi-permanent listener, that stays actively listening for the data until you remove it.
If you want to only read the value once, and then stop listening for change, you should use:
currentAthleteRef.addListenerForSingleValueEvent(...
Overall though: if the new value depends on the current value in the same database location, you should use a transaction to prevent concurrent updates from overwriting each other.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论