Tesis 1.0.0
Loading...
Searching...
No Matches
PersonalDataFragment.java
Go to the documentation of this file.
1package com.example.food_front;
2
3import android.app.ProgressDialog;
4import android.content.Intent;
5import android.os.Bundle;
6import android.util.Log;
7import android.view.LayoutInflater;
8import android.view.View;
9import android.view.ViewGroup;
10import android.widget.Button;
11import android.widget.EditText;
12import android.widget.TextView;
13import android.widget.Toast;
14
15import androidx.annotation.NonNull;
16import androidx.annotation.Nullable;
17import androidx.cardview.widget.CardView;
18import androidx.fragment.app.Fragment;
19
20import com.android.volley.AuthFailureError;
21import com.android.volley.Request;
22import com.android.volley.RequestQueue;
23import com.android.volley.Response;
24import com.android.volley.VolleyError;
25import com.android.volley.toolbox.JsonObjectRequest;
26import com.android.volley.toolbox.Volley;
27import com.example.food_front.utils.ProfileManager;
28import com.example.food_front.utils.SessionManager;
29
30import org.json.JSONException;
31import org.json.JSONObject;
32
33import java.util.HashMap;
34import java.util.Map;
35
36public class PersonalDataFragment extends Fragment {
37
38 private TextView tvNombre, tvApellido, tvEmail, tvTelefono, tvDireccion;
39 private EditText etNombre, etApellido, etEmail, etTelefono, etDireccion;
40 private Button btnEdit, btnSave, btnCancel, btnRefreshPersonalData;
41 private CardView viewModeCard, editModeCard;
42
43 private ProfileManager profileManager;
44 private SessionManager sessionManager;
45 private RequestQueue requestQueue;
46 private static final String UPDATE_URL = "https://backmobile1.onrender.com/appUSERS/update/";
47 private static final String TAG = "PersonalDataFragment";
48
50 // Required empty public constructor
51 }
52
53 @Nullable
54 @Override
55 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
56 View view = inflater.inflate(R.layout.fragment_personal_data, container, false);
57
58 // Inicializar RequestQueue
59 requestQueue = Volley.newRequestQueue(requireContext());
60
61 // Inicializar ProfileManager y SessionManager
62 profileManager = new ProfileManager(requireContext());
63 sessionManager = new SessionManager(requireContext());
64
65 // Inicializar las vistas - Modo visualización
66 viewModeCard = view.findViewById(R.id.view_mode_card);
67 tvNombre = view.findViewById(R.id.tv_nombre);
68 tvApellido = view.findViewById(R.id.tv_apellido);
69 tvEmail = view.findViewById(R.id.tv_email);
70 tvTelefono = view.findViewById(R.id.tv_telefono);
71 tvDireccion = view.findViewById(R.id.tv_direccion);
72 btnEdit = view.findViewById(R.id.btn_edit);
73 btnRefreshPersonalData = view.findViewById(R.id.btn_refresh_personal_data);
74
75 // Inicializar las vistas - Modo edición
76 editModeCard = view.findViewById(R.id.edit_mode_card);
77 etNombre = view.findViewById(R.id.et_nombre);
78 etApellido = view.findViewById(R.id.et_apellido);
79 etEmail = view.findViewById(R.id.et_email);
80 etTelefono = view.findViewById(R.id.et_telefono);
81 etDireccion = view.findViewById(R.id.et_direccion);
82 btnSave = view.findViewById(R.id.btn_save);
83 btnCancel = view.findViewById(R.id.btn_cancel);
84
85 // Obtener datos frescos del backend
86 fetchUserDataFromBackend();
87
88 // Configurar el botón de edición
89 btnEdit.setOnClickListener(v -> switchToEditMode());
90
91 // Configurar el botón de guardar
92 btnSave.setOnClickListener(v -> updateUserData());
93
94 // Configurar el botón de cancelar
95 btnCancel.setOnClickListener(v -> switchToViewMode());
96
97 // Configurar el botón de actualización de datos personales
98 btnRefreshPersonalData.setOnClickListener(v -> refreshUserDataFromBackend());
99
100 return view;
101 }
102
107 private void fetchUserDataFromBackend() {
108 // En lugar de solicitar al backend, usamos los datos que ya guardamos durante el login
109 Log.d(TAG, "Utilizando datos guardados localmente desde el login");
110
111 // Mostrar un diálogo de progreso breve para mantener la experiencia de usuario
112 ProgressDialog progressDialog = new ProgressDialog(requireContext());
113 progressDialog.setMessage("Cargando datos...");
114 progressDialog.show();
115
116 try {
117 // Simular un breve retraso para mejor experiencia de usuario
118 new android.os.Handler().postDelayed(() -> {
119 progressDialog.dismiss();
120
121 // Simplemente mostrar los datos que ya tenemos guardados
122 displayPersonalData();
123
124 Toast.makeText(requireContext(), "Datos cargados correctamente", Toast.LENGTH_SHORT).show();
125 }, 300); // Retraso de 300ms para que el diálogo sea visible
126
127 } catch (Exception e) {
128 progressDialog.dismiss();
129 Log.e(TAG, "Error al cargar datos locales: " + e.getMessage());
130 Toast.makeText(requireContext(), "Error al cargar los datos del usuario", Toast.LENGTH_SHORT).show();
131 displayPersonalData(); // Mostrar datos almacenados localmente como respaldo
132 }
133 }
134
135 private void displayPersonalData() {
136 // Obtener datos del ProfileManager
137 String nombre = profileManager.getName();
138 String apellido = profileManager.getSurname();
139 String email = profileManager.getEmail();
140 String telefono = profileManager.getPhone();
141 String direccion = profileManager.getAddress(); // Obtener dirección
142
143 // Mostrar los datos en los TextViews
144 tvNombre.setText(nombre != null ? nombre : "No disponible");
145 tvApellido.setText(apellido != null ? apellido : "No disponible");
146 tvEmail.setText(email != null ? email : "No disponible");
147 tvTelefono.setText(telefono != null ? telefono : "No disponible");
148 tvDireccion.setText(direccion != null ? direccion : "No disponible"); // Mostrar dirección
149 }
150
151 private void switchToEditMode() {
152 // Cargar los datos actuales en los campos de edición
153 etNombre.setText(profileManager.getName());
154 etApellido.setText(profileManager.getSurname());
155 etEmail.setText(profileManager.getEmail());
156 etTelefono.setText(profileManager.getPhone());
157 etDireccion.setText(profileManager.getAddress()); // Cargar dirección
158
159 // Cambiar la visibilidad de las tarjetas
160 viewModeCard.setVisibility(View.GONE);
161 editModeCard.setVisibility(View.VISIBLE);
162 }
163
164 private void switchToViewMode() {
165 // Cambiar la visibilidad de las tarjetas
166 editModeCard.setVisibility(View.GONE);
167 viewModeCard.setVisibility(View.VISIBLE);
168 }
169
170 private void updateUserData() {
171 // Mostrar diálogo de progreso mientras se actualiza
172 ProgressDialog progressDialog = new ProgressDialog(requireContext());
173 progressDialog.setMessage("Actualizando datos...");
174 progressDialog.setCancelable(false);
175 progressDialog.show();
176
177 // Obtener los valores ingresados
178 String nombre = etNombre.getText().toString().trim();
179 String apellido = etApellido.getText().toString().trim();
180 String email = etEmail.getText().toString().trim();
181 String telefono = etTelefono.getText().toString().trim();
182 String direccion = etDireccion.getText().toString().trim(); // Obtener dirección
183
184 // Validar campos
185 if (nombre.isEmpty() || apellido.isEmpty() || email.isEmpty()) {
186 Toast.makeText(requireContext(), "Por favor, completa todos los campos obligatorios", Toast.LENGTH_SHORT).show();
187 progressDialog.dismiss();
188 return;
189 }
190
191 // Crear JSON con los datos del usuario
192 JSONObject requestData = new JSONObject();
193 try {
194 requestData.put("nombre", nombre);
195 requestData.put("apellido", apellido);
196 requestData.put("email", email);
197 requestData.put("telefono", telefono);
198
199 // Probar con múltiples variaciones del campo de dirección para cubrir posibles requerimientos del backend
200 requestData.put("direccion", direccion);
201 requestData.put("address", direccion); // Nombre alternativo en inglés
202 requestData.put("direccion_entrega", direccion); // Posible nombre específico
203
204 // Mostrar el JSON que estamos enviando para depuración
205 Log.d("UpdateUser", "JSON enviado: " + requestData.toString());
206 } catch (JSONException e) {
207 e.printStackTrace();
208 progressDialog.dismiss();
209 Toast.makeText(requireContext(), "Error al preparar los datos", Toast.LENGTH_SHORT).show();
210 return;
211 }
212
213 // Crear la solicitud
214 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
215 Request.Method.PUT,
216 UPDATE_URL,
217 requestData,
218 new Response.Listener<JSONObject>() {
219 @Override
220 public void onResponse(JSONObject response) {
221 Log.d("UpdateUser", "Respuesta: " + response.toString());
222 progressDialog.dismiss();
223 try {
224 // Verificar si la respuesta contiene un indicador de éxito
225 // Algunos servidores devuelven "success", otros "status" o "code"
226 if (response.has("success")) {
227 boolean success = response.getBoolean("success");
228 if (success) {
229 handleSuccessfulUpdate(nombre, apellido, email, telefono, direccion);
230 } else {
231 String error = response.optString("error", "Error desconocido");
232 Toast.makeText(requireContext(), "Error: " + error, Toast.LENGTH_SHORT).show();
233 }
234 } else {
235 // Si no hay campo "success", asumimos que la operación fue exitosa
236 // ya que obtuvimos una respuesta sin errores
237 handleSuccessfulUpdate(nombre, apellido, email, telefono, direccion);
238 }
239 } catch (JSONException e) {
240 e.printStackTrace();
241 Toast.makeText(requireContext(), "Error al procesar la respuesta", Toast.LENGTH_SHORT).show();
242 }
243 }
244 },
245 new Response.ErrorListener() {
246 @Override
247 public void onErrorResponse(VolleyError error) {
248 progressDialog.dismiss();
249 String errorMsg = "Error al actualizar los datos. ";
250
251 // Intentar obtener más información sobre el error
252 if (error.networkResponse != null) {
253 errorMsg += "Código: " + error.networkResponse.statusCode;
254
255 // Intentar obtener el cuerpo de la respuesta de error
256 try {
257 String responseBody = new String(error.networkResponse.data, "utf-8");
258 Log.e("UpdateUser", "Error response: " + responseBody);
259 errorMsg += " - " + responseBody;
260 } catch (Exception e) {
261 Log.e("UpdateUser", "Error al leer el cuerpo del error", e);
262 }
263 }
264
265 Log.e("UpdateUser", errorMsg, error);
266 Toast.makeText(requireContext(), errorMsg, Toast.LENGTH_SHORT).show();
267 }
268 }
269 ) {
270 @Override
271 public Map<String, String> getHeaders() throws AuthFailureError {
272 Map<String, String> headers = new HashMap<>();
273 // Añadir token de autenticación si existe
274 String token = sessionManager.getToken();
275 if (token != null) {
276 headers.put("Authorization", "Bearer " + token);
277 // Mostrar el token que estamos usando para depuración
278 Log.d("UpdateUser", "Token enviado: " + token);
279 } else {
280 Log.e("UpdateUser", "No hay token disponible");
281 }
282 headers.put("Content-Type", "application/json");
283 return headers;
284 }
285 };
286
287 // Configurar timeout más largo para la solicitud
288 jsonObjectRequest.setRetryPolicy(new com.android.volley.DefaultRetryPolicy(
289 30000, // 30 segundos de timeout
290 0, // sin reintentos
291 com.android.volley.DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
292 ));
293
294 // Añadir solicitud a la cola
295 requestQueue.add(jsonObjectRequest);
296 }
297
298 private void refreshUserDataFromBackend() {
299 ProgressDialog progressDialog = new ProgressDialog(requireContext());
300 progressDialog.setMessage("Actualizando datos...");
301 progressDialog.setCancelable(false);
302 progressDialog.show();
303
304 String url = "https://backmobile1.onrender.com/appUSERS/me/";
305 String token = sessionManager.getToken();
306
307 JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
308 response -> {
309 progressDialog.dismiss();
310 try {
311 String nombre = response.optString("nombre", "");
312 String apellido = response.optString("apellido", "");
313 String email = response.optString("email", "");
314 String telefono = response.optString("telefono", "");
315 String direccion = response.optString("direccion", "");
316 String profileImageUrl = response.optString("imagen_perfil_url", profileManager.getProfileImageUrl());
317 profileManager.saveInfo(nombre, apellido, email, telefono, profileImageUrl, direccion);
318 displayPersonalData();
319 Toast.makeText(requireContext(), "Datos actualizados", Toast.LENGTH_SHORT).show();
320 } catch (Exception e) {
321 Toast.makeText(requireContext(), "Error al actualizar datos", Toast.LENGTH_SHORT).show();
322 }
323 },
324 error -> {
325 progressDialog.dismiss();
326 Toast.makeText(requireContext(), "Error al conectar con el servidor", Toast.LENGTH_SHORT).show();
327 }) {
328 @Override
329 public Map<String, String> getHeaders() throws AuthFailureError {
330 Map<String, String> headers = new HashMap<>();
331 headers.put("Authorization", "Bearer " + token);
332 return headers;
333 }
334 };
335 requestQueue.add(request);
336 }
337
338 private void handleSuccessfulUpdate(String nombre, String apellido, String email, String telefono, String direccion) {
339 // Mantener la URL de la imagen de perfil existente
340 String profileImageUrl = profileManager.getProfileImageUrl();
341
342 // Actualizar datos en ProfileManager con la dirección y la imagen de perfil correctamente separadas
343 profileManager.saveInfo(nombre, apellido, email, telefono, profileImageUrl, direccion);
344
345 Log.d("UpdateUser", "Datos guardados localmente - Nombre: " + nombre +
346 ", Apellido: " + apellido +
347 ", Email: " + email +
348 ", Teléfono: " + telefono +
349 ", Dirección: " + direccion +
350 ", URL de imagen: " + profileImageUrl);
351
352 // Actualizar la vista
353 displayPersonalData();
354 switchToViewMode();
355
356 Toast.makeText(requireContext(), "Datos actualizados correctamente", Toast.LENGTH_SHORT).show();
357 }
358}
View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
void saveInfo(String name, String surname, String email, String phone)