Товар добавляется в список разное количество раз - PullRequest
0 голосов
/ 13 октября 2018

Я использую Firebase в моем приложении для Android.Я делаю вызовы между двумя пользователями в приложении.Когда первый пользователь запускает вызов, он появляется у второго игрока, а также у текущего пользователя. Другими словами, я делаю историю вызовов для обоих пользователей.У списка странное поведение со мной.Иногда это прекрасно работает, как я и исключал, но в другой раз, когда добавлялся новый вызов, он добавлял его в список 2 раза, 4 раза или 9 раз.Я отладил свой код, чтобы увидеть, если проблема в адаптере, но я обнаружил, что проблема в размере списка.Я много пытался понять причину этого странного поведения, но не смог.

это код, который выводит данные и отображает их:

    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) {
                        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("Logging", "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("Logging", "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();
        completedChallengesList.add(0, challenge);
        view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
    } else if (challenge.getState().equals(refusedChallengeText)) {
        view.showCompletedChallengesTv();
        completedChallengesList.add(0, challenge);
        view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
    } else if (challenge.getState().equals(uncompletedChallengeText)) {
        view.showUncompletedChallengesTv();
        uncompletedChallengesList.add(0, challenge);
        view.notifyAdapters(completedChallengesList.size(), uncompletedChallengesList.size());
    }

    return player1Uid;
}

и этоПросмотр функций:

    @Override
public void startUnCompletedChallengesAdapter(ArrayList uncompletedChallengesList) {
    if(uncompletedChallengesRecyclerView.getAdapter() == null) {
        uncompletedChallengeRecyclerAdapter = new ChallengesAdapter(uncompletedChallengesList, getActivity());
        RecyclerView.LayoutManager uncompletedChallengesLayoutManager = new LinearLayoutManager(getActivity());
        uncompletedChallengesRecyclerView.setLayoutManager(uncompletedChallengesLayoutManager);
        uncompletedChallengesRecyclerView.setItemAnimator(new DefaultItemAnimator());
        uncompletedChallengesRecyclerView.setAdapter(uncompletedChallengeRecyclerAdapter);
    }
}

@Override
public void startCompletedChallengesAdapter(ArrayList completedChallengesList) {
    if(completedChallengesRecyclerView.getAdapter() == null) {
        completedChallengeRecyclerAdapter = new ChallengesAdapter(completedChallengesList, getActivity());
        RecyclerView.LayoutManager completedChallengesLayoutManager = new LinearLayoutManager(getActivity());
        completedChallengesRecyclerView.setLayoutManager(completedChallengesLayoutManager);
        completedChallengesRecyclerView.setItemAnimator(new DefaultItemAnimator());
        completedChallengesRecyclerView.setAdapter(completedChallengeRecyclerAdapter);
    }
}

@Override
public void notifyAdapters(int completedListSize, int uncompletedListSize) {
    completedChallengesRecyclerView.removeAllViews();
    uncompletedChallengesRecyclerView.removeAllViews();
    completedChallengeRecyclerAdapter.notifyDataSetChanged();
    uncompletedChallengeRecyclerAdapter.notifyDataSetChanged();
    Toast.makeText(getActivity(), "completed list size : " + completedListSize
            + ", uncompleted list size : " + uncompletedListSize, Toast.LENGTH_SHORT).show();
}

@Override
public void onDataFound() {
    hideProgressBar();
    noChallengesTv.setVisibility(android.view.View.GONE);
    noInternetConnectionText.setVisibility(android.view.View.GONE);
}

@Override
public void hideProgressBar() {
    if(progressBar.getVisibility() != View.GONE){
        progressBar.setVisibility(android.view.View.GONE);
    }
}

@Override
public void hideUncompletedChallengesTv() {
    uncompletedChallengesTv.setVisibility(android.view.View.GONE);
}

@Override
public void hideCompletedChallengesTv() {
    completeChallengesTv.setVisibility(android.view.View.GONE);
}

@Override
public void showCompletedChallengesTv() {
    completeChallengesTv.setVisibility(android.view.View.VISIBLE);
}

@Override
public void showUncompletedChallengesTv() {
    uncompletedChallengesTv.setVisibility(android.view.View.VISIBLE);
}

@Override
public void hideNoChallengesTv() {
    noChallengesTv.setVisibility(View.GONE);
}
@Override
public void showNoChallengesTv() {
    noChallengesTv.setVisibility(View.VISIBLE);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...