Tesis 1.0.0
Loading...
Searching...
No Matches
ProductsFragment.java
Go to the documentation of this file.
1package com.example.food_front;
2
3import android.os.Bundle;
4import android.util.Log;
5import android.view.LayoutInflater;
6import android.view.View;
7import android.view.ViewGroup;
8import android.widget.Toast;
9import androidx.annotation.NonNull;
10import androidx.annotation.Nullable;
11import androidx.fragment.app.Fragment;
12import androidx.recyclerview.widget.LinearLayoutManager;
13import androidx.recyclerview.widget.RecyclerView;
14
15import com.android.volley.Request;
16import com.android.volley.RequestQueue;
17import com.android.volley.Response;
18import com.android.volley.VolleyError;
19import com.android.volley.toolbox.StringRequest;
20import com.android.volley.toolbox.Volley;
21import com.example.food_front.adapters.ProductoAdapter;
22import com.example.food_front.models.Carrito;
23import com.example.food_front.models.Producto;
24import com.example.food_front.utils.SessionManager;
25
26import org.json.JSONArray;
27import org.json.JSONException;
28import org.json.JSONObject;
29
30import java.util.ArrayList;
31import java.util.HashMap;
32import java.util.List;
33import java.util.Map;
34
35public class ProductsFragment extends Fragment {
36
37 private RecyclerView recyclerView;
38 private ProductoAdapter adapter;
39 private List<Producto> productList;
40
41 @Override
42 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
43 View view = inflater.inflate(R.layout.fragment_products, container, false);
44 recyclerView = view.findViewById(R.id.recyclerview_producto);
45 recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
46
47 productList = new ArrayList<>();
48 adapter = new ProductoAdapter(productList, new ProductoAdapter.OnProductoClickListener() {
49 @Override
50 public void onAgregarCarritoClick(Producto producto) {
51 Toast.makeText(getContext(), "Producto agregado al carrito", Toast.LENGTH_SHORT).show();
52 // Agregar producto al carrito en la base de datos
53 agregarProductoAlCarrito(producto.getIdProducto()); // Cambia la cantidad según sea necesario
54 }
55 });
56
57 recyclerView.setAdapter(adapter);
58
59 // Obtener el id de la categoría desde los argumentos (si existe)
60 int categoriaId = 0;
61 if (getArguments() != null) {
62 categoriaId = getArguments().getInt("categoria_id", 0);
63 }
64 cargarProductos(categoriaId);
65
66 return view;
67 }
68
69 // Modificado para recibir el id de la categoría
70 private void cargarProductos(int categoriaId) {
71 String url = "https://backmobile1.onrender.com/api/producto/";
72
73 StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
74 new Response.Listener<String>() {
75 @Override
76 public void onResponse(String response) {
77 try {
78 // Parsear el JSON
79 JSONArray jsonArray = new JSONArray(response);
80 productList.clear();
81
82 for (int i = 0; i < jsonArray.length(); i++) {
83 JSONObject jsonObject = jsonArray.getJSONObject(i);
84
85 // Obtener los detalles del producto desde el JSON
86 int id_producto = jsonObject.getInt("id_producto");
87 String nombre_producto = jsonObject.getString("nombre_producto");
88 String descripcion = jsonObject.getString("descripcion");
89 double precio = jsonObject.getDouble("precio");
90 String imagenUrl = jsonObject.getString("imageURL");
91 int id_categoria = jsonObject.has("id_categoria") ? jsonObject.getInt("id_categoria") : 0;
92
93 // Filtrar por categoría si corresponde
94 if (categoriaId == 0 || id_categoria == categoriaId) {
95 Producto producto = new Producto(id_producto, nombre_producto, descripcion, precio, imagenUrl, id_categoria);
96 productList.add(producto); // Añadir a la lista
97 }
98 }
99
100 // Notificar al adaptador que los datos han cambiado
101 adapter.notifyDataSetChanged();
102
103 } catch (JSONException e) {
104 e.printStackTrace();
105 Log.e("ProductsFragment", "Error al parsear el JSON: " + e.getMessage());
106 }
107 }
108 }, new Response.ErrorListener() {
109 @Override
110 public void onErrorResponse(VolleyError error) {
111 Log.e("ProductsFragment", "Error en la solicitud: " + error.getMessage());
112 Toast.makeText(getContext(), "Error al cargar productos", Toast.LENGTH_SHORT).show();
113 }
114 });
115
116 // Añadir la solicitud a la cola
117 Volley.newRequestQueue(getContext()).add(stringRequest);
118 }
119
120 private void agregarProductoAlCarrito(int idProducto) {
121 String url = "https://backmobile1.onrender.com/appCART/agregar/" + idProducto + "/";
122
123 SessionManager sessionManager = new SessionManager(getContext());
124 String token = sessionManager.getToken();
125 Log.d("AuthToken", "Token usado en la solicitud: " + token);
126
127 if (token != null) {
128 StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
129 response -> {
130 // Maneja la respuesta aquí, por ejemplo, muestra un mensaje de éxito
131 Toast.makeText(getContext(), "Producto agregado al carrito en la base de datos", Toast.LENGTH_SHORT).show();
132 },
133 error -> {
134 // Maneja el error aquí
135 Log.e("ProductsFragment", "Error al agregar al carrito: " + error.getMessage());
136 if (error.networkResponse != null) {
137 Log.e("ProductsFragment", "Código de respuesta: " + error.networkResponse.statusCode);
138 }
139 Toast.makeText(getContext(), "Error al agregar producto al carrito", Toast.LENGTH_SHORT).show();
140 }) {
141 @Override
142 public Map<String, String> getHeaders() {
143 Map<String, String> headers = new HashMap<>();
144 headers.put("Authorization", "Bearer " + token); // Usa el token almacenado
145 Log.d("HeadersDebug", "Headers: " + headers); // Verificar que se envíen los headers
146 return headers;
147 }
148
149 @Override
150 protected Map<String, String> getParams() {
151 Map<String, String> params = new HashMap<>();
152 params.put("direccion", "casa"); // Dirección hardcodeada
153 params.put("cantidad", "1"); // Cantidad fija
154 Log.d("ParamsDebug", "Params: " + params); // Verificar que se envíen los parámetros
155 return params;
156 }
157 };
158
159 // Añadir la solicitud a la cola
160 Volley.newRequestQueue(getContext()).add(stringRequest);
161 } else {
162 // Maneja el caso en que no hay token
163 Toast.makeText(getContext(), "Debes iniciar sesión para agregar productos al carrito", Toast.LENGTH_SHORT).show();
164 }
165 }
166}
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)