简体   繁体   English

RecyclerView 项目,具有来自多个 arrayList 的数据,在重新启动片段时重复

[英]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.我在一个片段中有 recyclerView,该片段由来自三个不同 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.即使我在运行向它们添加数据的方法之前清除了三个 arrayLists,当再次打开这个片段时,recyclerView 的项目也会重复。 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 .尝试改变你的代码以清除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.如果这不起作用,请评估您在什么时候调用您的public pegarExec() function,因为这可能会被多次调用。

See: The lifecycle diagram @ https://developer.android.com/guide/components/fragments参见:生命周期图@ 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.这与问题无关,但请尝试在 onViewCreated 而不是 onCreateView 中进行工作,因为您将在尝试使用上下文时在 onCreateView 中遇到更多崩溃。

@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.我对正在发生的事情的猜测是,当您拉取值时,您的数据正在发生变化/移动,这导致项目被多次添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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