Implement "onClickListener" in RecyclerView working with Cursor

1

A few days ago I asked a question asking for help and guidance on how to create a RecyclerView with a CursorAdapter to be able to create a list where% data RecyclerView were extracted from the internal DB (in SQLite) from the app itself. Here the link of the question.

Today, I wanted to implement the onClickListener method so that, when the user clicks on an item in the list, a new Activity will open where all the data of that item will appear.

By logic and by several failed Internet examples, I have to implement the onClickListener within the adapter of RecyclerView and, from there, take the data _id of the item selected, consult the data of that record and pass it to the new Activity for a Intent , but I can not get this _id of the item.

How do I get the _id of the selected item? Am I forgetting something? I'm doing it wrong? Is the onClickListener method not implemented in RecyclerAdapter or yes? Can you really implement onClickListener or you have to use OnItemTouchListener if it is in RecyclerView according to the Google Documentation ?

This is the adapter code of RecyclerView extending from CursorRecyclerViewAdapter<ListsAdapter.ViewHolder> :

public class ListsAdapter extends CursorRecyclerViewAdapter<ListsAdapter.ViewHolder>{

    Cursor c;
    Context context;
    Cursor cursor;

    //Constructor
    public ListsAdapter(Context context, Cursor cursor) {
        super(context, cursor);
        this.context = context;
        this.cursor = cursor;
        c = cursor;
    }

    // Para enlazar el diseño del ítem a la lista
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.design_item_list, parent, false);
        return new ViewHolder(itemView, context);
    }

    // Para declarar las variables del layout seleccionado y poder llenarlas después
    // Aquí he implementado el "OnClickListener"
    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView title, delivery, aux;
        Context context;
        Cursor cursor;

        public ViewHolder(View itemView, Context context) {
            super(itemView);
            this.context = context;
            itemView.setOnClickListener(this);
            title = (TextView) itemView.findViewById(R.id.title_item);
            delivery = (TextView) itemView.findViewById(R.id.delivery);
            aux = (TextView) itemView.findViewById(R.id.date);
        }

        // Aquí es donde se supone tengo que coger el _id del registro del cursor, pero no se como. También tengo que abrir la nueva activity, pasandole los datos del registro del cursor por un un intent.
        @Override
        public void onClick(View v) {
            // Aquí necesito de alguna forma coger el _id y hacer 
            // aparecer la nueva activity

            ArrayList<String> data = selectData();
            Intent intent = new Intent(context, ItemDetailsHomeworkActivity.class);
            intent.putExtra("datos", data);
            context.startActivity(intent);
        }

        // Desde aquí queria obtener los datos del cursor, pero al no saber
        // como coger el _id no puedo obtener esos datos.
        // Se supone que tendría que pasar como dato sobrecargado el _id.
        private ArrayList<String> selectData(){
            ArrayList<String> data = new ArrayList<>();
            data.add(cursor.getString(0));// _ID - Integer
            data.add(cursor.getString(1));// Nombre del deber
            data.add(cursor.getString(2));// Nombre del tipo de deber
            data.add(cursor.getString(3));// tieneNota - Booleano
            data.add(cursor.getString(4));// Descripcion
            data.add(cursor.getString(5));// Fecha entrega
            data.add(cursor.getString(6));// Hora de entrega
            data.add(cursor.getString(7));// Ubicacion
            data.add(cursor.getString(8));// Grado de tipo de prioridad
            data.add(cursor.getString(9));// Nombre de la asignatura
            data.add(cursor.getString(10));// Calificación
            data.add(cursor.getString(11));// Terminado - Booleano

            return data;
        }
    }

    @Override
    public void onBindViewHolder(ListsAdapter.ViewHolder holder, Cursor cursor) {

        holder.title.setText(cursor.getString(1));
        holder.delivery.setText(cursor.getString(9));
        if (cursor.getString(5).equals("null")) {
            holder.aux.setText("");
        } else {
            holder.aux.setText(cursor.getString(5));
        }
            holder.cursor = cursor;

    }

    @Override
    public int getItemCount() {
        if (c != null) {
            return c.getCount();
        }
        return 0;
    }

}

I hope you can help me or that someone has created something similar in your project and can answer me and explain the questions I have asked.

Thanks in advance to everyone.

    
asked by Vicky Vicent 10.06.2016 в 16:13
source

1 answer

1

As I put in my code, you can implement a onClickListener without any problem.

The only problem I had was that I needed to take the BD record corresponding to the selected item that was saved in a Cursor and I got an answer.

This has been the solution:

    @Override
    public void onClick(View v) {
        // Cojo la posición del ítem del ArrayList
        int position = this.getAdapterPosition();
        // Le paso la posición al método "selectData()"
        ArrayList<String> data = selectData(position);
        Intent intent = new Intent(context, ItemDetailsHomeworkActivity.class);
        intent.putExtra("datos", data);
        context.startActivity(intent);
    }

    private ArrayList<String> selectData(int position){
        ArrayList<String> data = new ArrayList<>();
        switch (tab) {
            case "deber-unfinished":
                // Muevo el cursor a la posición y empiezo a guardar datos
                cursor.moveToPosition(position);
                data.add(cursor.getString(0));// _ID - Integer
                data.add(cursor.getString(1));// Nombre del deber
                data.add(cursor.getString(2));// Nombre del tipo de deber
                data.add(cursor.getString(3));// tieneNota - Booleano
                data.add(cursor.getString(4));// Descripcion
                data.add(cursor.getString(5));// Fecha entrega
                data.add(cursor.getString(6));// Hora de entrega
                data.add(cursor.getString(7));// Ubicacion
                data.add(cursor.getString(8));// Grado de tipo de prioridad
                data.add(cursor.getString(9));// Nombre de la asignatura
                data.add(cursor.getString(10));// Calificación
                data.add(cursor.getString(11));// Terminado - Booleano
                break;
        }
        return data;
    }
}

So I take the data in the Activity that collects the Intent *:

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {//ver si contiene datos
        data = (ArrayList<String>) getIntent().getSerializableExtra("datos");

        title.setText(data.get(1));
        type.setText(data.get(2));
        priority.setText(data.get(8));
        aux = data.get(5) + " - " + data.get(6);
        delivery.setText(aux);
        description.setText(data.get(4));
        location.setText(data.get(7));
        subject.setText(data.get(9));
        aux = data.get(3);
        System.out.println("tieneNota es: " + aux);
        mark.setText(data.get(10));
    }

Where I had gotten confused was that I needed the _id of the record to be able to access it, but no, because if the SELECT that I got the records to be able to fill the list has 3 records, in the list will have 3 records and no more, so if I get the position of the selected item I will have the record, just need to move through the courses and go.

Sorry for the inconvenience because of the question, I'm going against the clock with this app and I'm on my nerves. In the end it was silly, but I do not want to leave the question for people who want to implement this or create a onClickListener in their RecyclerView . So we enrich this community.

* I had also had a small problem with having to pass ArrayList through Intent , but thanks to x4mp73r I solved it.

Thank you very much everyone.

    
answered by 10.06.2016 / 21:29
source