Curso App para Pizzería con delivery
¿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:
.....
Route::post('productos', [JsonController::class,'productos']);
.....
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'
}
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;
}
}
<?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
)
);
......
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);
}
}
}
.....
/// Extraer los productos por categoría
@POST("productos")
Call<ArrayList<Producto>> getProductos(
@Header("Authorization") String access_token,
@Query("categoria_id") int categoria_id
);
.....
<?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>
.....
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) {
}
});
}
......
@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();
}
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 fuente del proyecto adquiriendo el curso completo
Comprar© Copyright Codea::App Cursos de Programación Online | LATAM | 2020 - 2024