how to send a data from a recyclerView to an Activity? How to return this data to the recyclerView if it is modified in the activity?

1

Hi, I am new to Android, and I have not yet been able to solve a problem I have. Code a recyclrerViewAdapter that allows me to display a list of products on the screen. I want to emphasize that this list of items has the options to add products or remove them.

The code is as follows:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {

    Context context;
    ArrayList<Productos> items;

    String cantidadProductos;


    public RecyclerViewAdapter(Context context, ArrayList<Productos> items) {
        this.context = context;
        this.items = items;
    }

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

        View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
        RecyclerViewHolder viewHolder = new RecyclerViewHolder(view);
        return viewHolder;
    }

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

        holder.img_item.setImageResource(items.get(position).getImagen());

        holder.cardView.setOnClickListener(onClickListener);
        holder.cardView.setTag(holder);

        holder.setOnclickListener();

    }

    View.OnClickListener onClickListener = (new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            RecyclerViewHolder sh = (RecyclerViewHolder) view.getTag();
            int posicion = sh.getAdapterPosition();

            cantidadProductos = Integer.toString(sh.cont);

            Intent intent = new Intent(context, DialogoActivity.class);
            intent.putExtra("imagen", items.get(posicion).getImagen());
            intent.putExtra("nombre", items.get(posicion).getNombre());
            intent.putExtra("precio", items.get(posicion).getPrecio());
            intent.putExtra("cantidadProductos", cantidadProductos);
            context.startActivity(intent);

        }
    });

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

and on the screen you see something like this:

This would be the RecyclerViewHolder where you implement the methods that allow you to add or decrease the products:

public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {


    ImageView img_item;
    ImageButton btn_add, btn_remove;
    TextView cantidad_producto;
    CardView cardView;

    int cont = 0;

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

        img_item = (ImageView) itemView.findViewById(R.id.img_items);
        btn_add = (ImageButton) itemView.findViewById(R.id.btn_agregar);
        btn_remove = (ImageButton) itemView.findViewById(R.id.btn_remover);
        cantidad_producto = (TextView) itemView.findViewById(R.id.cantidad_agregada);
        cardView = (CardView) itemView.findViewById(R.id.onClickItems);
    }

    public void setOnclickListener(){
        btn_remove.setOnClickListener(this);
        btn_add.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_agregar){
            cont++;

        }else if (view.getId() == R.id.btn_remover && cont > 0){
            cont--;
        }else if (view.getId() == R.id.btn_remover && cont == 0){
            Toast.makeText(view.getContext(),"No puede eliminar los productos", Toast.LENGTH_SHORT).show();
        }
        cantidad_producto.setText(Integer.toString(cont));
    }
}

by clicking on one of the items of products shown in the previous image, an activity that works as a dialogue is opened, and it receives and shows the user more detail of the products:

As you can see, this dialog allows you to modify also the amount of products that can be added. We already manage to send the quantity data from the item to the dialog, but I do not know how to resend this data from the activity to the items that are in the recyclerVewAdapter.

this would be the activity code:

public class DialogoActivity extends Activity implements View.OnClickListener {

    ImageView imagen;
    TextView nombre, precio, cantidadProductos;
    ImageButton btn_remove, btn_add;

    int cont;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialogo);

        imagen = (ImageView) findViewById(R.id.img_dialog);
        nombre = (TextView) findViewById(R.id.titulo_dialog);
        precio = (TextView) findViewById(R.id.precio_dialog);
        cantidadProductos = (TextView) findViewById(R.id.text_cantidad);
        btn_add = (ImageButton) findViewById(R.id.btn_dialog_agregar);
        btn_remove = (ImageButton) findViewById(R.id.btn_dialog_remover);

        Intent intent = getIntent();
        int imagenProducto = intent.getExtras().getInt("imagen");
        String nombreProducto = intent.getExtras().getString("nombre");
        String precioProducto = intent.getExtras().getString("precio");
        String cantidad = intent.getExtras().getString("cantidadProductos");

        cont = Integer.parseInt(cantidad);

        imagen.setImageResource(imagenProducto);
        nombre.setText(nombreProducto);
        precio.setText(precioProducto);
        cantidadProductos.setText(cantidad);

        setOnClickListener();

    }

    public void setOnClickListener(){
        btn_remove.setOnClickListener(this);
        btn_add.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_dialog_agregar){
            cont++;

        }else if (view.getId() == R.id.btn_dialog_remover && cont > 0){
            cont--;
        }else if (view.getId() == R.id.btn_dialog_remover && cont == 0){
            Toast.makeText(view.getContext(),"No puede eliminar los productos", Toast.LENGTH_SHORT).show();
        }
        cantidadProductos.setText(Integer.toString(cont));
    }
}

I appreciate the help you offer me ...

    
asked by Hamin 14.06.2018 в 23:57
source

1 answer

1
  

How to send a data from a recyclerView to an Activity?

1. RecyclerViewAdapter

You need to replace this line:

context.startActivity(intent);

For this one:

startActivityForResult(intent, 1); //el 1 es un id de requestcode 

To make the dialog return data.

2. DialogoActivity

Now you need to collect the data you want to send back to the RecyclerView. I imagine that you close your dialogue by pressing the back button, so you should pick it up there:

@Override
public void onBackPressed()
{
     super.onBackPressed();
     Intent returnIntent = new Intent();
     returnIntent.putExtra("result",cantidadProductos.getText()); //añadimos al intent de retorno el valor que deseas retornar
     setResult(Activity.RESULT_OK,returnIntent);
     finish(); 
}

3. MainActivity (or as you have called your activity that contains the recyclerview)

Finally, you will need to recover the data in the original Activity, for that you need to rewrite the method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if (requestCode == 1) { //aqui comprobando el requestcode = 1 antes mencionado
      if(resultCode == Activity.RESULT_OK){
          String resultadoDevuelto=data.getStringExtra("result"); //recupera tu dato proveniente del dialog
      }
  }
}//onActivityResult
  

How to return this data to the recyclerView if it is modified in the   activity?

The variable resultadoDevuelto that I put just in the previous code contains your modified number from the dialog. You have it in your MainActivity and you would have to add it in the recyclerview using your recyclerview adapter , creating a new method such as adaptador.setItemCantidad(resultado) in your adapter.

One more thing, you may need to send in the whole process what is the position of the item to modify in the recyclerview, that is, if it is the first hamburger, the second, the third, etc. Then you also spend it in adaptador.setItemCantidad(resultado, posicion) and you can now modify the correct burger with the correct amount!

Links of interest:

  • Get the result of an activity
  • Return an intent with result by pressing the Back button
  • answered by 15.06.2018 в 00:55