简体   繁体   中英

RecyclerView items, with data from multiple arrayList, are been repeated when the fragment it is restarted

I have recyclerView in a fragment that is populated by data from three different arrayLists. Even if i clear the three arrayLists before running the method that adds data to them, items of the recyclerView will be repeated whem this fragment is opens again. How can I solve it?

My fragment:

public class execFragment extends Fragment {
    private RecyclerView recyclerView;
    private String nomeAluno, teste="", exec="", jaaj, disc;
    private DatabaseReference reference = FirebaseDatabase.getInstance().getReference("usuarios/");
    private DatabaseReference referenceExec = FirebaseDatabase.getInstance().getReference("salas/");
    private ArrayList<String> listaExercicio;
    private TextView txtPendente;
    private ArrayList<String> listaSalas;
    private ArrayList<String> listData;
    private ArrayList<String> listaDisc;
    private EditText edtPesquisa;
    private Date currentTime;
    private int count= 0;
    private adapterExec adapterExec;
    private ArrayList<String> nomeSalas = new ArrayList<String>();

    private DatabaseReference referencePegarExec, referencePegarDisc;

    public execFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_exec, container, false);

        recyclerView= view.findViewById(R.id.recyclerView);
        edtPesquisa= view.findViewById(R.id.edtPesquisa);
        txtPendente= view.findViewById(R.id.txtPendente);
        final Context context = view.getContext();
        listaExercicio= new ArrayList<>();
        listaSalas= new ArrayList<>();
        listData= new ArrayList<>();
        listaDisc= new ArrayList<>();

        // edtPesquisa.requestFocus();
        // configurar adpater
        adapterExec= new adapterExec(listaExercicio, listaDisc, listData,context);
        //  adapterSalas adapterExec= new adapterSalas(listaExercicio, context);
        //configurar recycler view
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        // recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayout.VERTICAL));
        recyclerView.setAdapter( adapterExec );

        //evento click
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(context, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {

                        // Toast.makeText(context, "Item selecionado: " + exercicio.getNomeAtv(),Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getActivity(), resolverExecActivity.class);
                        intent.putExtra("nomeSala", listaSalas.get(position));
                        intent.putExtra("nomeExec", listaExercicio.get(position));
                        startActivity(intent);
                    }

                    @Override
                    public void onLongItemClick(View view, int position) {

                        //  Toast.makeText(context, "Click longo: "  + exercicio.getNomeAtv(),Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getActivity(), resolverExecActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    }
                })
        );

        return view;

    }

    @Override
    public void onStart() {
        super.onStart();
        listaExercicio.clear();
        listaSalas.clear();
        listData.clear();
        listaDisc.clear();
        pegarExec();
    }


    public void pegarExec(){

        FirebaseAuth autenticacao = FirebaseAuth.getInstance();
        String emailUsu = autenticacao.getCurrentUser().getEmail();
        reference.orderByChild("email").equalTo(emailUsu).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot datas : dataSnapshot.getChildren()) {
                    nomeAluno = datas.child("nome").getValue().toString();
                    referenceExec.orderByChild("alunos/"+ nomeAluno+"/codigo").equalTo(nomeAluno).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            if(dataSnapshot.exists()){

                                for (DataSnapshot datas : dataSnapshot.getChildren()) {
                                    teste= datas.getKey();
                                    nomeSalas.add(teste);

                                }
                                for(int i = 0; i < nomeSalas.size();i++ ) {
                                    referencePegarExec = FirebaseDatabase.getInstance().getReference("salas/" + nomeSalas.get(i) );
                                    final int finalI = i;

                                    referencePegarExec.child("exercicios").addValueEventListener(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                            for (DataSnapshot dsp : dataSnapshot.getChildren()) {
                                                jaaj = dsp.getKey();
                                                if (!jaaj.equals("1")) {

                                                    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                                                    Date strDate = null;
                                                    try {
                                                        strDate = sdf.parse(dataSnapshot.child(jaaj + "/dataValidade").getValue(String.class));
                                                    } catch (ParseException e) {
                                                        e.printStackTrace();
                                                    }
                                                    if (System.currentTimeMillis() < strDate.getTime()) {

                                                        listaSalas.add(nomeSalas.get(finalI));
                                                        listData.add(dataSnapshot.child(jaaj + "/dataValidade").getValue(String.class));
                                                        listaExercicio.add(jaaj);

                                                        referencePegarDisc = FirebaseDatabase.getInstance().getReference("salas/" + nomeSalas.get(finalI) );
                                                        referencePegarDisc.child("disciplina").addValueEventListener(new ValueEventListener() {
                                                            @Override
                                                            public void onDataChange(@NonNull DataSnapshot snap) {
                                                                disc= snap.getValue(String.class);
                                                                listaDisc.add(disc);
                                                                adapterExec.notifyDataSetChanged();
                                                            }

                                                            @Override
                                                            public void onCancelled(@NonNull DatabaseError databaseError) {

                                                            }
                                                        });
                                                    }
                                                }
                                            }



                                        }

                                        @Override
                                        public void onCancelled(@NonNull DatabaseError databaseError) {

                                        }
                                    });
                                }//adapterExec.notifyDataSetChanged();

                            }else{
                                txtPendente.setText("Nenhum exercício pendente");
                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {
                            throw databaseError.toException();
                        }
                    });

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                throw databaseError.toException();
            }
        }); 
    }
}

My adapter:

public class adapterExec extends RecyclerView.Adapter<adapterExec.MyViewHolder> {

    private ArrayList<String> listaExercicio;
    private ArrayList<String> listaDic;
    private ArrayList<String> listaData;
    private Context context;


    public adapterExec(ArrayList<String> listaExercicio, ArrayList<String> listaDic, ArrayList<String> listaData, Context context) {
        this.listaExercicio = listaExercicio;
        this.listaDic = listaDic;
        this.listaData = listaData;
        this.context = context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View itemLista = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.adapterexec_lista, parent, false);

        return new MyViewHolder(itemLista);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.nomeAtv.setText(listaExercicio.get(position));
        holder.dataVenc.setText(listaData.get(position));
        holder.materia.setText(listaDic.get(position));

    }

    @Override
    public int getItemCount() {
        return listaExercicio.size();
    }
    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        TextView nomeAtv;
        TextView dataVenc;
        TextView materia;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            nomeAtv= itemView.findViewById(R.id.textNomeAtv);
            dataVenc=itemView.findViewById(R.id.textDataVenc);
            materia= itemView.findViewById(R.id.textMateria);
        }
    }

}

Try shifting your code to clear things to be in the onResume .

If that doesn't work, evaluate at what point you are calling your public pegarExec() function, because that may be being called more than once.

See: The lifecycle diagram @ https://developer.android.com/guide/components/fragments

This is irrelevant to the question but try to do your work in onViewCreated instead of onCreateView as you will get more crashes in onCreateView trying to work with context.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_exec, container, false);
    return view;
}


@Override
public void onViewCreated(View view, Bundle onSaveInstanceState) {
     super.onViewCreated(view, onSaveInstanceState);
     recyclerView= view.findViewById(R.id.recyclerView);
     edtPesquisa= view.findViewById(R.id.edtPesquisa);
     txtPendente= view.findViewById(R.id.txtPendente);
     final Context context = view.getContext();
     listaExercicio= new ArrayList<>();
     listaSalas= new ArrayList<>();
     listData= new ArrayList<>();
     listaDisc= new ArrayList<>();
    // edtPesquisa.requestFocus();
     // configurar adpater
     adapterExec= new adapterExec(listaExercicio, listaDisc, listData,context);
   //  adapterSalas adapterExec= new adapterSalas(listaExercicio, context);
     //configurar recycler view
     RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
     recyclerView.setLayoutManager(layoutManager);
    // recyclerView.setHasFixedSize(true);
     recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayout.VERTICAL));
     recyclerView.setAdapter( adapterExec );

     //evento click
     recyclerView.addOnItemTouchListener(
       new RecyclerItemClickListener(context, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
           @Override
           public void onItemClick(View view, int position) {

              // Toast.makeText(context, "Item selecionado: " + exercicio.getNomeAtv(),Toast.LENGTH_SHORT).show();
               Intent intent = new Intent(getActivity(), resolverExecActivity.class);
               intent.putExtra("nomeSala", listaSalas.get(position));
               intent.putExtra("nomeExec", listaExercicio.get(position));
               startActivity(intent);
           }

           @Override
           public void onLongItemClick(View view, int position) {

             //  Toast.makeText(context, "Click longo: "  + exercicio.getNomeAtv(),Toast.LENGTH_SHORT).show();
               Intent intent = new Intent(getActivity(), resolverExecActivity.class);
               startActivity(intent);
           }

           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

           }
       })
);


}

My Guess as to what's happening is that your data is changing/shifting as you pull the values and that's causing the items to be added multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM