Tesis 1.0.0
Loading...
Searching...
No Matches
LoginFragment.java
Go to the documentation of this file.
1package com.example.food_front;
2
3import android.content.Context;
4import android.os.Bundle;
5import android.util.Log;
6import android.view.LayoutInflater;
7import android.view.View;
8import android.view.ViewGroup;
9import android.widget.Button;
10import android.widget.EditText;
11import android.widget.TextView;
12import android.widget.Toast;
13
14import androidx.annotation.NonNull;
15import androidx.annotation.Nullable;
16import androidx.fragment.app.Fragment;
17import androidx.fragment.app.FragmentManager;
18import androidx.fragment.app.FragmentTransaction;
19
20import com.android.volley.Request;
21import com.android.volley.RequestQueue;
22import com.android.volley.Response;
23import com.android.volley.VolleyError;
24import com.android.volley.toolbox.JsonObjectRequest;
25import com.android.volley.toolbox.Volley;
26import com.bumptech.glide.Glide;
27import com.example.food_front.utils.ProfileManager;
28import com.example.food_front.utils.SessionManager;
29
30import org.json.JSONException;
31import org.json.JSONObject;
32
33public class LoginFragment extends Fragment {
34
35 private EditText etCorreo, etPassword;
36 private SessionManager sessionManager;
37 private ProfileManager profileManager;
38
39 @Nullable
40 @Override
41 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
42 View view = inflater.inflate(R.layout.fragment_login, container, false);
43
44 // Inicializar las vistas
45 etCorreo = view.findViewById(R.id.etCorreo);
46 etPassword = view.findViewById(R.id.etPassword);
47 Button btnLogin = view.findViewById(R.id.btnLogin);
48 TextView tvRegister = view.findViewById(R.id.tvRegister);
49
50 sessionManager = new SessionManager(requireContext());
51 profileManager = new ProfileManager(requireContext());
52
53 // Agregar el click listener al boton de login
54 btnLogin.setOnClickListener(new View.OnClickListener() {
55 @Override
56 public void onClick(View v) {
57 performLogin();
58 }
59 });
60
61 // Agregar el click listener al texto de registro
62 tvRegister.setOnClickListener(new View.OnClickListener() {
63 @Override
64 public void onClick(View v) {
65 replaceFragment(new RegisterFragment());
66 }
67 });
68
69 return view;
70 }
71
72 private void performLogin() {
73 String email = etCorreo.getText().toString().trim();
74 String password = etPassword.getText().toString().trim();
75
76 // Validar campos vacíos
77 if (email.isEmpty() || password.isEmpty()) {
78 Toast.makeText(getContext(), "Por favor, completa todos los campos", Toast.LENGTH_SHORT).show();
79 return;
80 }
81
82 // Validar correo electrónico
83 if (!isValidEmail(email)) {
84 Toast.makeText(getContext(), "Por favor, ingresa un correo electrónico válido", Toast.LENGTH_SHORT).show();
85 return;
86 }
87
88 String url = "https://backmobile1.onrender.com/appUSERS/login/";
89
90 // Crear el json que se enviará en el body
91 JSONObject requestBody = new JSONObject();
92 try {
93 requestBody.put("email", email);
94 requestBody.put("password", password);
95 } catch (JSONException e) {
96 e.printStackTrace();
97 return;
98 }
99
100 // Crear el request de volley
101 JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, requestBody,
102 new Response.Listener<JSONObject>() {
103 @Override
104 public void onResponse(JSONObject response) {
105 try {
106 String token = response.getString("access");
107 String name = response.getString("nombre");
108 String surname = response.getString("apellido");
109 String email = response.getString("email");
110 String phone = response.getString("telefono");
111 String profileImageUrl = response.optString("imagen_perfil_url", "");
112 String address = response.optString("direccion", ""); // <-- Nuevo campo
113
114 // Agregar log para ver la URL y dirección que viene del backend
115 Log.d("ImagenPerfil", "URL recibida del backend: " + profileImageUrl);
116 Log.d("LoginFragment", "Dirección recibida del backend: " + address);
117 Log.d("LoginFragment", "Email guardado en SessionManager: " + email);
118 sessionManager.saveToken(token); // Guardar el token para futuras solicitudes
119 sessionManager.saveEmail(email); // Guardar el email para futuras solicitudes
120 profileManager.saveInfo(name, surname, email, phone, profileImageUrl, address); // Guardar info incluyendo imagen y dirección
121
122 // Solo guardar la URL y reemplazar el fragmento
123 Toast.makeText(getContext(), "Inicio de sesión exitoso", Toast.LENGTH_SHORT).show();
124 replaceFragment(new HomeFragment());
125 } catch (JSONException e) {
126 e.printStackTrace();
127 Toast.makeText(getContext(), "Respuesta inválida del servidor", Toast.LENGTH_SHORT).show();
128 }
129 }
130 }, new Response.ErrorListener() {
131 @Override
132 public void onErrorResponse(VolleyError error) {
133 // Manejo de errores dependiendo del estado del servidor
134 String errorMessage = error.networkResponse != null && error.networkResponse.data != null
135 ? new String(error.networkResponse.data)
136 : "Error en el inicio de sesión";
137
138 if (errorMessage.contains("non_field_errors")) {
139 Toast.makeText(getContext(), "Usuario no se reconoció o no existe. Por favor, regístrate.", Toast.LENGTH_LONG).show();
140 } else {
141 Toast.makeText(getContext(), errorMessage, Toast.LENGTH_SHORT).show();
142 }
143 }
144 });
145
146 // Agregar la request a la queue de Volley
147 RequestQueue queue = Volley.newRequestQueue(requireContext());
148 queue.add(request);
149 }
150
151 private boolean isValidEmail(String email) {
152 // Regex para validar el correo electrónico
153 String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
154 return email.matches(emailPattern);
155 }
156
157 public void saveUserProfile(String name, String surname, String email, String phone, String profileImageUrl) {
158 profileManager.saveInfo(name, surname, email, phone, profileImageUrl); // Guardar los datos del usuario
159 Toast.makeText(getContext(), "Datos guardados correctamente", Toast.LENGTH_SHORT).show();
160 }
161
162 private void replaceFragment(Fragment newFragment) {
163 FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();
164 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
165 fragmentTransaction.replace(R.id.fragment_container_view, newFragment);
166 fragmentTransaction.addToBackStack(null);
167 fragmentTransaction.commit();
168 }
169}
void saveUserProfile(String name, String surname, String email, String phone, String profileImageUrl)
View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)