Recycleview item returning the same data for all items when clicked

Asked

Viewed 318 times

0

I have a list of addresses in Recycleview and each address has its latitude and longitude coordinates retrieved from the bank. But when I click on the list item to start a route from the coordinates always brings the same in all items. What should I do? Follows my codes:

My Adapter:

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

private List<DadosSolicitacao> solicitacoes;
private Context context;

public AdapterSolicitacoes(List<DadosSolicitacao> listaSolicitacoes, Context c) {

    this.solicitacoes = listaSolicitacoes;
    this.context = c;

}

public class MyViewHolder extends RecyclerView.ViewHolder{

        TextView endereco;
        TextView material;
        TextView volume;
        Double latitude, longitude;


        public MyViewHolder(View itemView) {
            super(itemView);

            endereco = itemView.findViewById(R.id.tv_endereco);
            material = itemView.findViewById(R.id.tv_tipoMaterial);
            volume = itemView.findViewById(R.id.tv_volumeMaterial);

        }
    }

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemLista = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.adapter_lista_solicitacao, parent, false);

    return new MyViewHolder(itemLista);
}

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

    DadosSolicitacao dados = solicitacoes.get(position);

       holder.endereco.setText(dados.getEndereco());
       holder.material.setText(dados.getTipoMaterial());
       holder.volume.setText(dados.getVolumeMaterial());

}

@Override
public int getItemCount() {
    return solicitacoes.size();
}

}

Fragment where I retrieve the information and step into recycleview

   public class SolicRecebidaFragment extends Fragment {

private RecyclerView recyclerViewSolicRecebida;
private ArrayList<DadosSolicitacao> listaSolicRecebida = new ArrayList<>();
private AdapterSolicitacoes adapter;
private DatabaseReference refSolicRecebida;
private ValueEventListener valueEventoSolicitacao;
private DadosSolicitacao solicitacao;
private static final String TAG = "COORDENADAS";
private Double latitude, longitude;



public SolicRecebidaFragment() {
    // 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_solic_recebida, container, false);

    //Config.Inciais
    recyclerViewSolicRecebida = view.findViewById(R.id.recyclerView_ListaSolicitacao);

    //Referencia de recuperação de dados
    refSolicRecebida = ConfiguracaoFirebase.getFirebaseDataBase();

    //Config.Adapter
    adapter = new AdapterSolicitacoes(listaSolicRecebida, getActivity());

    //Config.RecyclerView
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerViewSolicRecebida.setLayoutManager(layoutManager);
    recyclerViewSolicRecebida.setHasFixedSize(true);
    recyclerViewSolicRecebida.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayout.VERTICAL));
    recyclerViewSolicRecebida.setAdapter(adapter);

    // Evento de clique do Item da Lista
    eventoClickItemLista();


    return view;

}

@Override //Exibi lista ao carregar o fragment
public void onStart() {
    super.onStart();

    recuperarSolicitacao();
}

@Override // Remove lista ao sair do fragment
public void onStop() {
    super.onStop();
    refSolicRecebida.removeEventListener(valueEventoSolicitacao);
}


public void recuperarSolicitacao() {

    valueEventoSolicitacao = refSolicRecebida.child("solicitacao_coleta").orderByChild("a_SolicAtendida")
            .equalTo("nao").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    listaSolicRecebida.clear();

                    for (DataSnapshot dados : dataSnapshot.getChildren()) {



                      // Log.i("LOG3: FDADOS", dataSnapshot.getValue().toString());
                       latitude = Double.valueOf(dados.child("latitude").getValue().toString());
                       longitude = Double.valueOf(dados.child("longitude").getValue().toString());



                        solicitacao = dados.getValue(DadosSolicitacao.class);
                        listaSolicRecebida.add(solicitacao);

                    }

                    adapter.notifyDataSetChanged();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

}

Click event

    public void eventoClickItemLista() {

    //Evento de click
    recyclerViewSolicRecebida.addOnItemTouchListener(
            new RecyclerItemClickListener(getActivity(), recyclerViewSolicRecebida,
                    new RecyclerItemClickListener.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {


                           //AlertDialog
    android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(getActivity());

    // Titulo do dialogo
    alertDialog.setTitle("Iniciar rota para coleta:");

    // Mensagem do dialogo
    alertDialog.setMessage("Ir para GPS?");

    // botao ir para GPS
    alertDialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {


            //Passar Latitude e Longitude e chamar GPS
            String strUri = "http://maps.google.com/maps?q=loc:" +
                    latitude + "," + longitude;

            Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                    Uri.parse(strUri));
            intent.setClassName("com.google.android.apps.maps",
                    "com.google.android.maps.MapsActivity");

            getActivity().startActivity(intent);
        }
    });

    // botao cancelar
    alertDialog.setNegativeButton("Não", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // visualizacao do dialogo
    alertDialog.show();


                        }

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





                        }

                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                        }
                    })
    );

}
  • Your click event is generic, is the msm for all items as I understood.

  • @Exactly Wotonsampaio. He is always picking up the coordinates of the last item that enters the list. I use the class you placed just below for the click event. Have some hint to make it dynamic and get the coordinates for each item?

1 answer

3


To add a click event to each separate item or you do it here:

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

    DadosSolicitacao dados = solicitacoes.get(position);

       holder.endereco.setText(dados.getEndereco());
       holder.material.setText(dados.getTipoMaterial());
       holder.volume.setText(dados.getVolumeMaterial());

       holder.endereco.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Seu código
        }
    });
}

Or does that class:

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);

        public void onLongItemClick(View view, int position);
    }

    GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && mListener != null) {
                    mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
                }
            }
        });
    }

    @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
            return true;
        }
        return false;
    }

    @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }

    @Override
    public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}

And in your action you call:

recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(Context, 
recyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                //Seu código
            }

            @Override
            public void onLongItemClick(View view, int i) {
              //Seu código
            }
        })
    );
  • I use the class you just put up for the click event. Have some hint to make it dynamic and get the coordinates for each item?

  • uses the first option so you make the click element for each separate item

  • as in that part has the position public void onBindViewHolder(MyViewHolder holder, int position) you know where to look for when you click on that item

  • Or using the class, in the onClick you also have the position: public void onItemClick(View view, int i) which is the i, just go get what you want on your list in that position

  • The first example is when you have multiple items within each recyclerView position and want to assign the click to a specific one

  • The second is for when you click on the recyclerView position, without considering the items within it

  • Get it another way. But thanks for the tip, cleared the mind so that the solution.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.