尝试更新数据库addValueEventListener

时间:2020-04-09 22:38:15

标签: java android firebase firebase-realtime-database

我正在尝试更新数据库。 我正在做的事情不起作用。在我第一次调用此方法时,它会更新数据库,但会完成活动。在我第二次调用该方法时,它陷入了无限循环。

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 :(得分:0)

我的快速猜测是,您希望只读取一次数据,并对其进行更新。但是,这不是您的代码所执行的操作:addValueEventListener添加了一个半永久性侦听器,该侦听器将一直主动侦听数据,直到将其删除为止。

如果只想读取一次该值,然后停止监听更改,则应使用:

currentAthleteRef.addListenerForSingleValueEvent(...

总体而言:如果新值取决于同一数据库位置中的当前值,则应use a transaction以防止并发更新相互覆盖。

相关问题