Capitulo 38 del Módulo 8 Catálogo de Productos

➜ Catálogo Productos

¿Cómo mostrar productos en una activity en Android con API Rest? | Vamos a cargar los productos correspondientes a una categoría en un RecyclerView con un Adaptador inflando los datos desde la API Rest.

Diseño e implementación de ProductosActivity

FUNCIÓN: Cargar los productos desde el servidor web y asignarles el evento click
LECCIÓN: ¿Cómo inflar un RecyclerView usando un Adapter con una API Rest?

Pasos:

  1. API Rest: Modificar la ruta productos de GET a POST en api.php
  2. Picasso: Integrar la librería Picasso en Gradle
  3. Clase: Implementar un modelo para productos{}
  4. Adapter: Agregar una vista producto.xml
  5. Adapter: Implementar una clase ProductoAdapter{}
  6. ApiService: Agregar el método getProductos()
  7. Listview: Agregar el ListView id=recyclerViewProducto
  8. Listview: Crear el método getListaProductos() 
  9. ListView: Inflar el recyclerView
  10. ListView: Asignar el evento click a cada producto

API Rest: Modificar la ruta productos de GET a POST en api.php

.....
    Route::post('productos', [JsonController::class,'productos']);
.....

Picasso: Integrar la librería Picasso en Gradle

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.6.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.picasso:picasso:2.71828'

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

Clase: Implementar un modelo para productos{}

package codea.app.pizzeria9.models;

public class Producto {
    int id;
    String nombre;
    String descripcion;
    double precio;
    String urlfoto;
    int categoria_id;

    public Producto(int id, String nombre, String descripcion, double precio, String urlfoto, int categoria_id) {
        this.id = id;
        this.nombre = nombre;
        this.descripcion = descripcion;
        this.precio = precio;
        this.urlfoto = urlfoto;
        this.categoria_id = categoria_id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public double getPrecio() {
        return precio;
    }

    public void setPrecio(double precio) {
        this.precio = precio;
    }

    public String getUrlfoto() {
        return urlfoto;
    }

    public void setUrlfoto(String urlfoto) {
        this.urlfoto = urlfoto;
    }

    public int getCategoria_id() {
        return categoria_id;
    }

    public void setCategoria_id(int categoria_id) {
        this.categoria_id = categoria_id;
    }
}

Adapter: Agregar una vista producto.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.cardview.widget.CardView
        app:cardElevation="10dp"
        app:cardBackgroundColor="@color/tercerColor"
        android:layout_margin="10dp"
        app:cardCornerRadius="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:orientation="vertical"
            android:layout_marginBottom="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/rv_foto"
                android:padding="1dp"
                android:adjustViewBounds="false"
                android:scaleType="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <TextView
                android:layout_width="match_parent"
                android:textAlignment="center"
                android:textSize="20dp"
                android:textColor="@color/white"
                android:text="hola"
                android:layout_height="wrap_content"
                android:id="@+id/rv_precio"/>
            <TextView
                android:layout_width="match_parent"
                android:textAlignment="center"
                android:textSize="18dp"
                android:textColor="@color/white"
                android:layout_height="wrap_content"
                android:id="@+id/rv_nombre"/>

        </LinearLayout>

    </androidx.cardview.widget.CardView>
</androidx.appcompat.widget.LinearLayoutCompat>
...
private RecyclerView recyclerView;
....

....
recyclerView = findViewById(R.id.recyclerViewProducto);
        recyclerView.setLayoutManager(
                new GridLayoutManager(
                        ProductosActivity.this,
                        2
                )
        );
......

Adapter: Implementar una clase ProductoAdapter{}

class ProductoAdapter extends RecyclerView.Adapter<ProductoAdapter.ProductoViewHolder>{

    Context context;
    List<Producto> productoList;

    public ProductoAdapter(Context context, List<Producto> productoList) {
        this.context = context;
        this.productoList = productoList;
    }

    @NonNull
    @Override
    public ProductoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.producto,null,false);
        return  new ProductoAdapter.ProductoViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ProductoViewHolder holder, int position) {
        holder.rv_nombre.setText(productoList.get(position).getNombre());
        holder.rv_precio.setText(""+productoList.get(position).getId());
        Picasso.get()
                .load(Config.BASE_URL_IMG+productoList.get(position).getUrlfoto())
                .into(holder.rv_foto);

        holder.rv_foto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(
                        new Intent(
                                context,
                                DetalleActivity.class
                        ).putExtra(
                                "producto_id",
                                productoList.get(position).getId()
                        )
                );
            }
        });
    }

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

    public class ProductoViewHolder extends RecyclerView.ViewHolder {
        ImageView rv_foto;
        TextView rv_nombre,rv_precio;
        public ProductoViewHolder(@NonNull View itemView) {
            super(itemView);
            rv_foto     =   itemView.findViewById(R.id.rv_foto);
            rv_nombre   =   itemView.findViewById(R.id.rv_nombre);
            rv_precio   =   itemView.findViewById(R.id.rv_precio);
        }
    }
}

ApiService: Agregar el método getProductos()

.....
/// Extraer los productos por categoría
    @POST("productos")
    Call<ArrayList<Producto>> getProductos(
            @Header("Authorization") String access_token,
            @Query("categoria_id") int categoria_id
    );
.....

Listview: Agregar el ListView id=recyclerViewProducto

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProductosActivity">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerViewProducto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </androidx.recyclerview.widget.RecyclerView>

</androidx.appcompat.widget.LinearLayoutCompat>

Listview: Crear el método getListaProductos() 

.....
private ArrayList<Producto> productoArrayList = new ArrayList<>();
private int categoria_id = 0;
......


.........
categoria_id = getIntent().getExtras().getInt("categoria_id");
.........


......
 public void getListaProductos(){
        Call<ArrayList<Producto>> call = RetrofitClient.getApiService().getProductos(
                "Bearer "+_sessionManager.getAccessToken(),
                categoria_id
        );
        call.enqueue(new Callback<ArrayList<Producto>>() {
            @Override
            public void onResponse(Call<ArrayList<Producto>> call, Response<ArrayList<Producto>> response) {
                if (response.isSuccessful()){
                    productoArrayList = response.body();
                    ProductoAdapter adapter = new ProductoAdapter(getApplicationContext(),productoArrayList);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<Producto>> call, Throwable t) {

            }
        });
    }
......

ListView: Inflar el recyclerView

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_productos);
        _sessionManager = new SessionManager(getApplicationContext());
        recyclerView = findViewById(R.id.recyclerViewProducto);
        recyclerView.setLayoutManager(
                new GridLayoutManager(
                        ProductosActivity.this,
                        2
                )
        );
        categoria_id = getIntent().getExtras().getInt("categoria_id");
        /// cargamos la lista de productos
        getListaProductos();

    }

ListView: Asignar el evento click a cada producto

class ProductoAdapter extends RecyclerView.Adapter<ProductoAdapter.ProductoViewHolder>{

............
    @Override
    public void onBindViewHolder(@NonNull ProductoViewHolder holder, int position) {
        ...........
        holder.rv_foto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(
                        new Intent(
                                context,
                                DetalleActivity.class
                        ).putExtra(
                                "producto_id",
                                productoList.get(position).getId()
                        )
                );
            }
        });
    }
..........
}

 


1499 visitas

Descarga el código del proyecto

Descarga el código fuente del proyecto adquiriendo el curso completo

Comprar

¡Qué aprenderás?

tooltip bs-tooltip-top bs-tooltip-end bs-tooltip-bottom bs-tooltip-start show fade tooltip-inner

Codea Applications

México, Colombia, España, Venezuela, Argentina, Bolivia, Perú