在子添加方法上工作多次

时间:2018-10-14 22:17:42

标签: java android firebase firebase-realtime-database listener

我正在使用Firebase数据库在应用程序中的两个用户之间挑战。在挑战中,我存储了player1Uid和player2Uid(player1是发起挑战的玩家,第二个玩家是接受或拒绝挑战的玩家)。我想记录挑战的历史记录,因此,如果挑战已完成,则将其存储在名为“ completedChallengesList”的列表中;如果挑战尚未完成,则将其存储在名为“未完成的挑战列表”的列表中。代码有时可以正常工作但是在其他情况下,它会将数据多次带入列表。

这是我带来数据的代码:

    public void startAsynkTask() {
    //TODO : search for a solution to this error
    AsyncTask asyncTask = new AsyncTask() {
        @Override
        protected Boolean doInBackground(Object[] objects) {
            try {
                Socket sock = new Socket();
                sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
                sock.close();
                return true;
            } catch (IOException e) {
                return false;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            if ((boolean) o) {
                clearLists();
                ChildEventListener generalChallengesListener = new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                        String challengeState = dataSnapshot.child("state").getValue().toString();
                        Log.v("Logging2", "onChildAdded");
                        if (challengeState.equals(uncompletedChallengeText)) {
                            getChallengeData(dataSnapshot, "onChildAdded");
                            view.onDataFound();
                        }
                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                        //TODO : note that the only changing handled is when challenge moves from uncompleted to completed state
                        getChallengeData(dataSnapshot, "onChildChanged");
                        for (int i = 0; i < uncompletedChallengesList.size(); i++) {
                            if (uncompletedChallengesList.get(i).getId().equals(dataSnapshot.getKey())) {
                                uncompletedChallengesList.remove(i);
                                view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
                                break;
                            }
                        }
                        checkListsSizeAndAdjustViews();
                        view.hideProgressBar();
                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {
                        startAsynkTask();
                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        //Toast.makeText(getActivity(), "فشل تحميل البيانات من فضلك تأكد من الاتصال بالانترنت", Toast.LENGTH_SHORT).show();
                        view.hideProgressBar();
                        Log.v("Logging", "error loading data : " + databaseError);
                    }
                };

                //this code gives data where current user is player 1
                player1Listener = challengesReference.orderByChild("player1Uid").equalTo(currentUserUid).addChildEventListener(generalChallengesListener);
                //this code gives data where current user is player 2
                player2Listener = challengesReference.orderByChild("player2Uid").equalTo(currentUserUid).addChildEventListener(generalChallengesListener);

                challengesReference.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        onInitialDataLoaded();
                        Log.v("ChallengesFragPresenter", "completed list size :" + completedChallengesList + " , uncompleted list size : " + uncompletedChallengesList);
                        challengesReference.removeEventListener(this);
                    }


                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
            } else {
                view.onNoInternetConnection();
            }
        }
    };

    asyncTask.execute();
}

public String getChallengeData(DataSnapshot dataSnapshot, String tag) {
    Log.v("ChallengesFragPresenter", "get challenge data called");
    Log.v("ChallengesFragPresenter", "completedChallengesList : " + completedChallengesList.size()
            + ", uncompletedChallengesList " + uncompletedChallengesList.size());
    view.startCompletedChallengesAdapter(completedChallengesList);
    view.startUnCompletedChallengesAdapter(uncompletedChallengesList);

    GenericTypeIndicator<List<Question>> t = new GenericTypeIndicator<List<Question>>() {
    };
    challenge = new Challenge();
    String challengeDate = dataSnapshot.child("date").getValue().toString();
    String challengeSubject = dataSnapshot.child("subject").getValue().toString();
    String challengeState = dataSnapshot.child("state").getValue().toString();
    String challengeId = dataSnapshot.getKey();
    ArrayList challengeQuestionsList = (ArrayList) dataSnapshot.child("questionsList").getValue(t);
    long player1Score = (long) dataSnapshot.child("player1score").getValue();
    long player2Score = (long) dataSnapshot.child("player2score").getValue();

    String player1Name = dataSnapshot.child("player1Name").getValue().toString();
    String player1Image = dataSnapshot.child("player1Image").getValue().toString();
    String player1Uid = dataSnapshot.child("player1Uid").getValue().toString();
    String player2Name = dataSnapshot.child("player2Name").getValue().toString();
    String player2Image = dataSnapshot.child("player2Image").getValue().toString();
    String player2Uid = dataSnapshot.child("player2Uid").getValue().toString();

    String challengerName, challengerImage;

    if (player1Uid.equals(currentUserUid)) {
        currentPlayer = 1;
        challengerName = player2Name;
        challengerImage = player2Image;
        challenge.setSecondChallengerUid(player2Uid);//second means that it is not the player who starts the challenge
        if (tag.equals("onChildAdded")) {
            player1childrenCount++;
        }
    } else {
        currentPlayer = 2;
        challengerName = player1Name;
        challengerImage = player1Image;
        challenge.setSecondChallengerUid(player1Uid);//second means that it is not the player who starts the challenge
        if (tag.equals("onChildAdded")) {
            player2childrenCount++;
        }
    }
    challenge.setCurrentPlayer(currentPlayer);
    challenge.setChallengerName(challengerName);
    challenge.setDate(challengeDate);
    challenge.setImage(challengerImage);
    challenge.setSubject(challengeSubject);
    challenge.setState(challengeState);
    challenge.setId(challengeId);
    challenge.setQuestionsList(challengeQuestionsList);
    String score;
    if (currentPlayer == 1) {
        score = player2Score + " : " + player1Score;
    } else {
        score = player1Score + " : " + player2Score;
    }
    challenge.setScore(score);
    if (challenge.getState().equals("اكتمل")) {
        view.showCompletedChallengesTv();
        if(!completedChallengesList.contains(challenge)) {
            completedChallengesList.add(0, challenge);
        }
        view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
    } else if (challenge.getState().equals(refusedChallengeText)) {
        view.showCompletedChallengesTv();
        if(!completedChallengesList.contains(challenge)) {
            completedChallengesList.add(0, challenge);
        }
        view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
    } else if (challenge.getState().equals(uncompletedChallengeText)) {
        view.showUncompletedChallengesTv();
        if(!uncompletedChallengesList.contains(challenge)) {
            uncompletedChallengesList.add(0, challenge);
        }
        view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
    }

    return player1Uid;
}

经过长时间的调试,我发现添加一个新的子对象时,多次调用getChallengeData()方法。我做了很多尝试来知道为什么,但是我做不到。

注意:我正在使用asynk任务在开始加载数据之前检查是否存在Internet连接。

1 个答案:

答案 0 :(得分:0)

我认为您的问题是,您没有删除列表程序“ generalChallengesListener”,因此将创建多个引用,因此onChildAdded将被多次重复删除,其数量取决于您创建的列表程序的数量。因此,添加对列表器的引用,并知道何时应删除它。 希望对您有帮助=)