Inicio » Cursos » App para Pizzería con delivery

Curso App para Pizzería con delivery

Capitulo 38 ➜ 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()
                        )
                );
            }
        });
    }
..........
}

 


1140 visitas

« Capítulo 37 – Categorías

Capítulo 39 – Detalle del Producto »

Descarga el código del proyecto

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

Comprar

Indice

Empezando el Proyecto
1 Planteamiento del Proyecto 2 Instalación de Laravel y configuración inicial
Panel de Administración
3 Auth y Roles de Usuario: Admin y Cliente 4 Implementación del CRUD de Categorías 5 Implementación CRUD Productos 6 Implementación CRUD Precios 7 Implementación CRUD Pedidos 8 Implementación CRUD Clientes
FrontEnd Diseño
9 Diseño de la Portada con productos 10 Diseño e implementación del Catálogo 11 Diseño Detalle del Producto
Carrito de Compra
12 Instalación del paquete del carrito de compra 13 Diseño de Notificación en la barra de menú 14 Diseño Resumen Carrito Lateral 15 Diseño de la vista Ver Carrito 16 Implementación Agregar Item 17 Incrementar Cantidad del Item 18 Decrementar la cantidad de un item 19 Remover un item del Carrito 20 Eliminar el carrito de compra 21 Confirmar y procesar el carrito de compra
API Rest
22 Planteamiento de la API Rest 23 Registro 24 Login 25 Logout 26 Categorías 27 Productos
Diseño de la App Android
28 Mockups del Aplicativo
Autenticación Android
29 Introducción a la Autenticación 30 ApiService 31 RetrofitClient 32 SessionManager 33 MainActivity 34 LoginActivity 35 RegisterActivity 36 Logout
Catálogo de Productos
37 Categorías 38 Productos 39 Detalle del Producto
Carrito de Compra Android
40 Creación de la DB dbpizza 41 Métodos de consulta a la DB 42 CarritoActivity 43 CarritoAdapter 44 AddItem 45 CarritoAll 46 UpdateItem 47 Subtotal, Impuesto y Total 48 Preparar el Pedido y enviarlo al Servidor 49 Vincular a WhatsApp y clearItems
Extras
50 Optimizando el diseño y funcionalidades

Más cursos que pueden interesarte

Más cursos

Codea Applications

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

© Copyright Codea::App Cursos de Programación Online | LATAM | 2020 - 2024