ja acabei a app acho?
This commit is contained in:
@@ -55,21 +55,23 @@ public class LoginActivity extends AppCompatActivity {
|
||||
String email = binding.emailEditText.getText().toString();
|
||||
String password = binding.passwordEditText.getText().toString();
|
||||
|
||||
/* if (email.equals("admin") && password.equals("123")) {
|
||||
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
|
||||
prefs.edit().putBoolean("is_logged_in", true).apply();
|
||||
// Mock data for admin
|
||||
String adminEmail = "admin@papcuida.com";
|
||||
prefs.edit().putString("user_email", adminEmail).apply();
|
||||
prefs.edit().putString("user_name", "Administrador").apply();
|
||||
|
||||
// Remove local Room admin creation since Room is gone
|
||||
|
||||
Toast.makeText(this, "Login de Administrador", Toast.LENGTH_SHORT).show();
|
||||
startActivity(new Intent(this, MainActivity.class));
|
||||
finish();
|
||||
return;
|
||||
}*/
|
||||
/*
|
||||
* if (email.equals("admin") && password.equals("123")) {
|
||||
* SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
|
||||
* prefs.edit().putBoolean("is_logged_in", true).apply();
|
||||
* // Mock data for admin
|
||||
* String adminEmail = "admin@papcuida.com";
|
||||
* prefs.edit().putString("user_email", adminEmail).apply();
|
||||
* prefs.edit().putString("user_name", "Administrador").apply();
|
||||
*
|
||||
* // Remove local Room admin creation since Room is gone
|
||||
*
|
||||
* Toast.makeText(this, "Login de Administrador", Toast.LENGTH_SHORT).show();
|
||||
* startActivity(new Intent(this, MainActivity.class));
|
||||
* finish();
|
||||
* return;
|
||||
* }
|
||||
*/
|
||||
|
||||
if (email.isEmpty() || password.isEmpty()) {
|
||||
Toast.makeText(this, "Preencha todos os campos", Toast.LENGTH_SHORT).show();
|
||||
@@ -85,31 +87,85 @@ public class LoginActivity extends AppCompatActivity {
|
||||
binding.loginButton.setText(R.string.login_button);
|
||||
|
||||
if (task.isSuccessful()) {
|
||||
// Sign in success
|
||||
// Sign in success, fetch from Firestore
|
||||
FirebaseUser user = mAuth.getCurrentUser();
|
||||
|
||||
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
|
||||
boolean rememberMe = binding.checkboxRememberMe.isChecked();
|
||||
|
||||
prefs.edit().putBoolean("is_logged_in", true).apply();
|
||||
prefs.edit().putBoolean("remember_me", rememberMe).apply();
|
||||
|
||||
// We can save user email/name from FirebaseUser if needed
|
||||
if (user != null) {
|
||||
prefs.edit().putString("user_email", user.getEmail()).apply();
|
||||
String displayName = user.getDisplayName();
|
||||
if (displayName != null) {
|
||||
prefs.edit().putString("user_name", displayName).apply();
|
||||
android.util.Log.d("LOGIN_DEBUG", "User authenticated: " + user.getUid());
|
||||
com.google.firebase.firestore.FirebaseFirestore.getInstance()
|
||||
.collection("utilizadores")
|
||||
.document(user.getUid())
|
||||
.get(com.google.firebase.firestore.Source.DEFAULT) // Try cache if offline
|
||||
.addOnCompleteListener(fetchTask -> {
|
||||
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
|
||||
boolean rememberMe = binding.checkboxRememberMe.isChecked();
|
||||
|
||||
prefs.edit().putBoolean("is_logged_in", true).apply();
|
||||
prefs.edit().putBoolean("remember_me", rememberMe).apply();
|
||||
|
||||
if (fetchTask.isSuccessful() && fetchTask.getResult() != null
|
||||
&& fetchTask.getResult().exists()) {
|
||||
com.google.firebase.firestore.DocumentSnapshot documentSnapshot = fetchTask
|
||||
.getResult();
|
||||
android.util.Log.d("LOGIN_DEBUG",
|
||||
"Firestore document fetched: " + documentSnapshot.exists());
|
||||
|
||||
String name = documentSnapshot.getString("name");
|
||||
String dbEmail = documentSnapshot.getString("email");
|
||||
android.util.Log.d("LOGIN_DEBUG",
|
||||
"Firestore Data -> Name: " + name + " Email: " + dbEmail);
|
||||
|
||||
if (name != null)
|
||||
prefs.edit().putString("user_name", name).apply();
|
||||
if (dbEmail != null)
|
||||
prefs.edit().putString("user_email", dbEmail).apply();
|
||||
} else {
|
||||
android.util.Log.d("LOGIN_DEBUG",
|
||||
"Firestore document missing or offline. Falling back...");
|
||||
if (!fetchTask.isSuccessful()) {
|
||||
android.util.Log.e("LOGIN_DEBUG", "Firestore fetch error",
|
||||
fetchTask.getException());
|
||||
}
|
||||
// Fallback to Auth data
|
||||
prefs.edit().putString("user_email", user.getEmail()).apply();
|
||||
if (user.getDisplayName() != null && !user.getDisplayName().isEmpty()) {
|
||||
prefs.edit().putString("user_name", user.getDisplayName()).apply();
|
||||
} else {
|
||||
// If even Auth display name is empty, fetch name from email prefix as a
|
||||
// last resort
|
||||
String email = user.getEmail();
|
||||
if (email != null && email.contains("@")) {
|
||||
String fallbackName = email.substring(0, email.indexOf("@"));
|
||||
prefs.edit().putString("user_name", fallbackName).apply();
|
||||
}
|
||||
}
|
||||
Toast.makeText(LoginActivity.this,
|
||||
"Aviso: A iniciar sessão offline ou sem perfil completo.",
|
||||
Toast.LENGTH_LONG).show();
|
||||
}
|
||||
|
||||
Toast.makeText(LoginActivity.this, "Bem-vindo!", Toast.LENGTH_SHORT).show();
|
||||
startActivity(new Intent(LoginActivity.this, MainActivity.class));
|
||||
finish();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
binding.loginButton.setEnabled(true);
|
||||
binding.loginButton.setText(R.string.login_button);
|
||||
|
||||
String errorMsg = task.getException() != null ? task.getException().getMessage()
|
||||
: "Erro desconhecido";
|
||||
if (errorMsg != null) {
|
||||
if (errorMsg.contains("invalid credential") || errorMsg.contains("password is invalid")
|
||||
|| errorMsg.contains("There is no user record")) {
|
||||
errorMsg = "Email ou palavra-passe incorretos.";
|
||||
} else if (errorMsg.contains("email address is badly formatted")) {
|
||||
errorMsg = "O formato do email é inválido.";
|
||||
} else if (errorMsg.contains("network")) {
|
||||
errorMsg = "Erro de rede. Verifique a sua ligação à internet.";
|
||||
}
|
||||
}
|
||||
|
||||
Toast.makeText(LoginActivity.this, "Bem-vindo!", Toast.LENGTH_SHORT).show();
|
||||
startActivity(new Intent(LoginActivity.this, MainActivity.class));
|
||||
finish();
|
||||
} else {
|
||||
// If sign in fails, display a message to the user.
|
||||
Toast.makeText(LoginActivity.this, "Falha na autenticação: " + task.getException().getMessage(),
|
||||
Toast.LENGTH_SHORT).show();
|
||||
Toast.makeText(LoginActivity.this, "Falha na autenticação: " + errorMsg, Toast.LENGTH_LONG)
|
||||
.show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -54,11 +54,11 @@ public class RegisterActivity extends AppCompatActivity {
|
||||
String userId = firebaseUser.getUid();
|
||||
|
||||
java.util.Map<String, Object> userMap = new java.util.HashMap<>();
|
||||
userMap.put("uid", userId);
|
||||
userMap.put("nome_completo", name);
|
||||
userMap.put("id", userId);
|
||||
userMap.put("name", name);
|
||||
userMap.put("email", email);
|
||||
userMap.put("idade", age);
|
||||
userMap.put("numero_utente", utenteStr);
|
||||
userMap.put("age", age);
|
||||
userMap.put("utenteNumber", utenteStr);
|
||||
userMap.put("profilePictureUri", ""); // Init empty
|
||||
|
||||
db.collection("utilizadores").document(userId)
|
||||
@@ -66,6 +66,7 @@ public class RegisterActivity extends AppCompatActivity {
|
||||
.addOnSuccessListener(aVoid -> {
|
||||
Toast.makeText(RegisterActivity.this, "Conta criada com sucesso!",
|
||||
Toast.LENGTH_SHORT).show();
|
||||
mAuth.signOut(); // Ensure user needs to login again
|
||||
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
|
||||
finish();
|
||||
})
|
||||
@@ -79,8 +80,18 @@ public class RegisterActivity extends AppCompatActivity {
|
||||
} else {
|
||||
binding.registerButton.setEnabled(true);
|
||||
binding.registerButton.setText("Registar");
|
||||
Toast.makeText(RegisterActivity.this, "Falha no registo: " + task.getException().getMessage(),
|
||||
Toast.LENGTH_SHORT).show();
|
||||
String errorMsg = task.getException() != null ? task.getException().getMessage()
|
||||
: "Erro desconhecido";
|
||||
if (errorMsg != null) {
|
||||
if (errorMsg.contains("email address is already in use")) {
|
||||
errorMsg = "Este email já está registado!";
|
||||
} else if (errorMsg.contains("email address is badly formatted")) {
|
||||
errorMsg = "O formato do email é inválido!";
|
||||
} else if (errorMsg.contains("Password should be at least")) {
|
||||
errorMsg = "A palavra-passe deve ter pelo menos 6 caracteres.";
|
||||
}
|
||||
}
|
||||
Toast.makeText(RegisterActivity.this, "Erro: " + errorMsg, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -27,9 +27,30 @@ public class HomeFragment extends Fragment {
|
||||
binding = FragmentHomeBinding.inflate(inflater, container, false);
|
||||
|
||||
// --- Greeting ---
|
||||
SharedPreferences prefs = requireContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
|
||||
String name = prefs.getString("user_name", "Utilizador");
|
||||
binding.textGreeting.setText("Olá, " + name + "!");
|
||||
com.google.firebase.auth.FirebaseAuth auth = com.google.firebase.auth.FirebaseAuth.getInstance();
|
||||
if (auth.getCurrentUser() != null) {
|
||||
String userId = auth.getCurrentUser().getUid();
|
||||
com.google.firebase.firestore.FirebaseFirestore.getInstance().collection("utilizadores").document(userId)
|
||||
.get()
|
||||
.addOnSuccessListener(documentSnapshot -> {
|
||||
if (documentSnapshot.exists() && isAdded()) {
|
||||
String name = documentSnapshot.getString("name");
|
||||
if (name != null && !name.isEmpty()) {
|
||||
// Extract first name
|
||||
String firstName = name.split(" ")[0];
|
||||
binding.textGreeting.setText("Olá, " + firstName + "!");
|
||||
} else {
|
||||
binding.textGreeting.setText("Olá, Utilizador!");
|
||||
}
|
||||
}
|
||||
})
|
||||
.addOnFailureListener(e -> {
|
||||
if (isAdded())
|
||||
binding.textGreeting.setText("Olá, Utilizador!");
|
||||
});
|
||||
} else {
|
||||
binding.textGreeting.setText("Olá, Utilizador!");
|
||||
}
|
||||
|
||||
// --- Next Medication ---
|
||||
medicationViewModel = new ViewModelProvider(this).get(MedicationViewModel.class);
|
||||
|
||||
@@ -169,34 +169,47 @@ public class ProfileFragment extends Fragment {
|
||||
currentUser.profilePictureUri = tempProfileUri.toString();
|
||||
}
|
||||
|
||||
// Warning: We update the email field in Firestore, but FirebaseAuth updateEmail
|
||||
// requires re-authentication usually.
|
||||
// Assuming simple data sync for now.
|
||||
currentUser.email = newEmail;
|
||||
Runnable saveToFirestore = () -> {
|
||||
currentUser.email = newEmail;
|
||||
String userId = auth.getCurrentUser().getUid();
|
||||
db.collection("utilizadores").document(userId)
|
||||
.set(currentUser)
|
||||
.addOnSuccessListener(aVoid -> {
|
||||
if (emailChanged) {
|
||||
getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString("user_email", newEmail)
|
||||
.apply();
|
||||
}
|
||||
|
||||
String userId = auth.getCurrentUser().getUid();
|
||||
db.collection("utilizadores").document(userId)
|
||||
.set(currentUser)
|
||||
.addOnSuccessListener(aVoid -> {
|
||||
if (emailChanged) {
|
||||
getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString("user_email", newEmail)
|
||||
.apply();
|
||||
}
|
||||
if (isAdded()) {
|
||||
loadUserData(); // Reload to show new image and data
|
||||
Toast.makeText(getContext(), "Dados atualizados com sucesso!", Toast.LENGTH_SHORT)
|
||||
.show();
|
||||
dialog.dismiss();
|
||||
dialogImageView = null;
|
||||
}
|
||||
})
|
||||
.addOnFailureListener(e -> {
|
||||
if (isAdded()) {
|
||||
Toast.makeText(getContext(), "Erro a guardar perfil.", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (isAdded()) {
|
||||
loadUserData(); // Reload to show new image and data
|
||||
Toast.makeText(getContext(), "Dados atualizados com sucesso!", Toast.LENGTH_SHORT).show();
|
||||
dialog.dismiss();
|
||||
dialogImageView = null;
|
||||
}
|
||||
})
|
||||
.addOnFailureListener(e -> {
|
||||
if (isAdded()) {
|
||||
Toast.makeText(getContext(), "Erro a guardar perfil.", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
if (emailChanged && auth.getCurrentUser() != null) {
|
||||
auth.getCurrentUser().updateEmail(newEmail)
|
||||
.addOnCompleteListener(task -> {
|
||||
if (task.isSuccessful()) {
|
||||
saveToFirestore.run();
|
||||
} else {
|
||||
Toast.makeText(getContext(), "Erro no email: " + task.getException().getMessage(),
|
||||
Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
saveToFirestore.run();
|
||||
}
|
||||
});
|
||||
|
||||
btnCancel.setOnClickListener(v -> {
|
||||
|
||||
Reference in New Issue
Block a user