Compare commits

..

6 Commits

Author SHA1 Message Date
86da99ee13 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	.idea/deploymentTargetSelector.xml
#	app/src/main/java/com/example/pap_findu/LocationService.java
#	app/src/main/java/com/example/pap_findu/login_activity.java
#	app/src/main/java/com/example/pap_findu/ui/map/MapFragment.java
2026-03-17 17:01:31 +00:00
d6e9320b80 a localizaçao esta funcionando + ou - certo 2026-03-13 16:57:14 +00:00
86221e5179 a localizaçao esta funcionando + ou - certo 2026-03-12 17:16:29 +00:00
fba454ce01 Merge remote-tracking branch 'origin/main' 2026-03-12 16:03:15 +00:00
d51fb4e580 a localizaçao esta funcionando + ou - certo 2026-03-12 16:02:59 +00:00
4055051755 a localizaçao esta funcionando + ou - certo 2026-03-12 16:00:54 +00:00
14 changed files with 1055 additions and 558 deletions

View File

@@ -7,10 +7,10 @@
</SelectionState> </SelectionState>
<SelectionState runConfigName="login_activity"> <SelectionState runConfigName="login_activity">
<option name="selectionMode" value="DIALOG" /> <option name="selectionMode" value="DIALOG" />
<DropdownSelection timestamp="2026-02-03T16:06:11.417598Z"> <DropdownSelection timestamp="2026-03-17T14:22:15.472961Z">
<Target type="DEFAULT_BOOT"> <Target type="DEFAULT_BOOT">
<handle> <handle>
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Medium_Phone_2.avd" /> <DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_7.avd" />
</handle> </handle>
</Target> </Target>
</DropdownSelection> </DropdownSelection>
@@ -18,12 +18,12 @@
<targets> <targets>
<Target type="DEFAULT_BOOT"> <Target type="DEFAULT_BOOT">
<handle> <handle>
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Medium_Phone_2.avd" /> <DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_7.avd" />
</handle> </handle>
</Target> </Target>
<Target type="DEFAULT_BOOT"> <Target type="DEFAULT_BOOT">
<handle> <handle>
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Medium_Phone.avd" /> <DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_7_filho.avd" />
</handle> </handle>
</Target> </Target>
</targets> </targets>

View File

@@ -4,15 +4,22 @@
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<queries>
<package android:name="com.google.android.gms" />
<intent>
<action android:name="com.google.android.geo.API_KEY" />
</intent>
</queries>
<application <application
android:allowBackup="true" android:allowBackup="true"
@@ -22,12 +29,17 @@
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.PAP_FindU"> android:theme="@style/Theme.PAP_FindU"
tools:targetApi="34">
<meta-data <meta-data
android:name="com.google.android.geo.API_KEY" android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAxen212OKqkfpu1AbWajLGTCTSdRhJWlM" /> android:value="AIzaSyAxen212OKqkfpu1AbWajLGTCTSdRhJWlM" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<service <service
android:name=".LocationService" android:name=".LocationService"
android:enabled="true" android:enabled="true"
@@ -37,9 +49,11 @@
<activity <activity
android:name=".CriarConta" android:name=".CriarConta"
android:exported="false" /> android:exported="false" />
<activity <activity
android:name=".Recuperar_Passe" android:name=".Recuperar_Passe"
android:exported="false" /> android:exported="false" />
<activity <activity
android:name=".ChatActivity" android:name=".ChatActivity"
android:exported="false" /> android:exported="false" />
@@ -56,6 +70,7 @@
<activity <activity
android:name=".AddZoneActivity" android:name=".AddZoneActivity"
android:exported="false" /> android:exported="false" />
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
@@ -64,6 +79,7 @@
<activity <activity
android:name=".EditProfileActivity" android:name=".EditProfileActivity"
android:exported="false" /> android:exported="false" />
<activity <activity
android:name=".SecurityActivity" android:name=".SecurityActivity"
android:exported="false" /> android:exported="false" />

View File

@@ -2,16 +2,24 @@ package com.example.pap_findu;
import android.os.Bundle; import android.os.Bundle;
import android.text.TextUtils; import android.text.TextUtils;
import android.view.View; import android.util.Log;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ImageButton; import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import com.example.pap_findu.adapters.ChatAdapter; import com.example.pap_findu.adapters.ChatAdapter;
import com.example.pap_findu.models.ChatMessage; import com.example.pap_findu.models.ChatMessage;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@@ -28,50 +36,101 @@ public class ChatActivity extends AppCompatActivity {
private ChatAdapter adapter; private ChatAdapter adapter;
private List<ChatMessage> messageList; private List<ChatMessage> messageList;
private DatabaseReference chatRef;
private String currentUserId;
private String accessCode;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.chat_activity); setContentView(R.layout.chat_activity);
// 1. Inicializar Firebase e User
currentUserId = FirebaseAuth.getInstance().getUid();
// Recuperamos o código da "sala" (partilhado entre pai e filho)
accessCode = getSharedPreferences("FindU_Prefs", MODE_PRIVATE)
.getString("child_access_code", null);
if (accessCode == null) {
Toast.makeText(this, "Erro: Sala de chat não encontrada", Toast.LENGTH_SHORT).show();
finish();
return;
}
// Caminho no Firebase: chats / 123456 / messages
chatRef = FirebaseDatabase.getInstance().getReference("chats")
.child(accessCode)
.child("messages");
// 2. Ligar Componentes do Teu Layout
recyclerChat = findViewById(R.id.recycler_chat); recyclerChat = findViewById(R.id.recycler_chat);
editChatMessage = findViewById(R.id.edit_chat_message); editChatMessage = findViewById(R.id.edit_chat_message);
btnSend = findViewById(R.id.btnSend); btnSend = findViewById(R.id.btnSend);
btnBack = findViewById(R.id.btnBack); btnBack = findViewById(R.id.btnBack);
// Initialize Message List with some dummy data // 3. Configurar RecyclerView e Adapter
messageList = new ArrayList<>(); messageList = new ArrayList<>();
messageList.add(new ChatMessage("Olá Miguel! Tudo bem?", true, "10:30"));
messageList.add(new ChatMessage("Cheguei bem à escola.", false, "10:32"));
messageList.add(new ChatMessage("Ainda bem! Qualquer coisa avisa.", true, "10:33"));
// Setup Adapter
adapter = new ChatAdapter(messageList); adapter = new ChatAdapter(messageList);
recyclerChat.setLayoutManager(new LinearLayoutManager(this)); recyclerChat.setLayoutManager(new LinearLayoutManager(this));
recyclerChat.setAdapter(adapter); recyclerChat.setAdapter(adapter);
// Scroll to bottom // 4. Lógica do Botão Enviar
recyclerChat.scrollToPosition(messageList.size() - 1);
// Send Button Logic
btnSend.setOnClickListener(v -> { btnSend.setOnClickListener(v -> {
String text = editChatMessage.getText().toString().trim(); String text = editChatMessage.getText().toString().trim();
if (!TextUtils.isEmpty(text)) { if (!TextUtils.isEmpty(text)) {
sendMessage(text); sendMessageToFirebase(text);
} }
}); });
// Back Button Logic // 5. Lógica do Botão Voltar
btnBack.setOnClickListener(v -> finish()); btnBack.setOnClickListener(v -> finish());
// 6. Começar a ouvir mensagens em tempo real
listenForMessages();
} }
private void sendMessage(String text) { private void sendMessageToFirebase(String text) {
String currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()); String currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
ChatMessage newMessage = new ChatMessage(text, true, currentTime);
messageList.add(newMessage); // Criamos a mensagem com o ID de quem envia
adapter.notifyItemInserted(messageList.size() - 1); ChatMessage newMessage = new ChatMessage(text, currentUserId, currentTime);
recyclerChat.scrollToPosition(messageList.size() - 1);
editChatMessage.setText(""); // "Empurramos" para o Firebase (Gera um ID único automático)
chatRef.push().setValue(newMessage)
.addOnSuccessListener(aVoid -> {
editChatMessage.setText(""); // Limpa o campo se correu bem
})
.addOnFailureListener(e -> {
Toast.makeText(this, "Erro ao enviar", Toast.LENGTH_SHORT).show();
});
}
private void listenForMessages() {
chatRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
messageList.clear();
for (DataSnapshot data : snapshot.getChildren()) {
ChatMessage msg = data.getValue(ChatMessage.class);
if (msg != null) {
// Se o senderId for o MEU, o adapter desenha à direita (azul)
msg.setSentByMe(msg.getSenderId().equals(currentUserId));
messageList.add(msg);
}
}
adapter.notifyDataSetChanged();
// Faz scroll automático para a última mensagem
if (messageList.size() > 0) {
recyclerChat.scrollToPosition(messageList.size() - 1);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e("ChatActivity", "Erro no Firebase: " + error.getMessage());
}
});
} }
} }

View File

@@ -2,46 +2,55 @@ package com.example.pap_findu;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.example.pap_findu.models.User;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.activity.EdgeToEdge; import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets; import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat; import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat; import androidx.core.view.WindowInsetsCompat;
import com.example.pap_findu.models.User;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class CriarConta extends AppCompatActivity { public class CriarConta extends AppCompatActivity {
private EditText inputFullName; private EditText inputFullName, emailEditText, passwordEditText, inputConfirmPassword;
private EditText emailEditText;
private EditText passwordEditText;
private EditText inputConfirmPassword;
private CheckBox checkTerms; private CheckBox checkTerms;
private Button btnCreateAccount; private Button btnCreateAccount;
private TextView loginLink; private TextView loginLink;
private com.google.firebase.auth.FirebaseAuth mAuth; private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
EdgeToEdge.enable(this); EdgeToEdge.enable(this);
setContentView(R.layout.activity_criar_conta); setContentView(R.layout.activity_criar_conta);
// Ajuste de Padding para EdgeToEdge
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets; return insets;
}); });
// Initialize views // 1. Inicializar Firebase
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference("users");
// 2. Inicializar Views
inputFullName = findViewById(R.id.inputFullName); inputFullName = findViewById(R.id.inputFullName);
emailEditText = findViewById(R.id.emailEditText); emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText); passwordEditText = findViewById(R.id.passwordEditText);
@@ -50,78 +59,69 @@ public class CriarConta extends AppCompatActivity {
btnCreateAccount = findViewById(R.id.btnCreateAccount); btnCreateAccount = findViewById(R.id.btnCreateAccount);
loginLink = findViewById(R.id.loginLink); loginLink = findViewById(R.id.loginLink);
mAuth = com.google.firebase.auth.FirebaseAuth.getInstance(); // 3. Botão Criar Conta
btnCreateAccount.setOnClickListener(v -> validarECriar());
// Set click listener for the create account button // 4. Link para Login
btnCreateAccount.setOnClickListener(new View.OnClickListener() { loginLink.setOnClickListener(v -> {
@Override startActivity(new Intent(CriarConta.this, login_activity.class));
public void onClick(View v) { finish();
String fullName = inputFullName.getText().toString();
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = inputConfirmPassword.getText().toString();
if (fullName.isEmpty() || email.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
Toast.makeText(CriarConta.this, "Por favor, preencha todos os campos.", Toast.LENGTH_SHORT).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(CriarConta.this, "As palavras-passe não coincidem.", Toast.LENGTH_SHORT).show();
} else if (!checkTerms.isChecked()) {
Toast.makeText(CriarConta.this, "Você deve concordar com os Termos de Serviço.", Toast.LENGTH_SHORT)
.show();
} else {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CriarConta.this,
new com.google.android.gms.tasks.OnCompleteListener<com.google.firebase.auth.AuthResult>() {
@Override
public void onComplete(
@androidx.annotation.NonNull com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(CriarConta.this, "Conta criada com sucesso!",
Toast.LENGTH_SHORT).show();
com.google.firebase.auth.FirebaseUser firebaseUser = mAuth
.getCurrentUser();
// Save user data to Realtime Database
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
DatabaseReference mDatabase = FirebaseDatabase.getInstance()
.getReference("users");
User user = new User(fullName, email);
mDatabase.child(userId).setValue(user)
.addOnCompleteListener(task1 -> {
if (!task1.isSuccessful()) {
Toast.makeText(CriarConta.this,
"Falha ao salvar dados do perfil.",
Toast.LENGTH_SHORT).show();
}
});
}
Intent intent = new Intent(CriarConta.this, MainActivity.class);
startActivity(intent);
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(CriarConta.this,
"Falha ao criar conta: " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
// Set click listener for the login link text
loginLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Navigate back to the login activity
Intent intent = new Intent(CriarConta.this, login_activity.class);
startActivity(intent);
finish();
}
}); });
} }
private void validarECriar() {
String fullName = inputFullName.getText().toString().trim();
String email = emailEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
String confirmPassword = inputConfirmPassword.getText().toString().trim();
// Validações Básicas
if (fullName.isEmpty() || email.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
Toast.makeText(this, "Preencha todos os campos!", Toast.LENGTH_SHORT).show();
return;
}
if (!password.equals(confirmPassword)) {
Toast.makeText(this, "As passwords não coincidem!", Toast.LENGTH_SHORT).show();
return;
}
if (!checkTerms.isChecked()) {
Toast.makeText(this, "Aceite os termos de serviço!", Toast.LENGTH_SHORT).show();
return;
}
// Criar no FirebaseAuth
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
salvarDadosNoPerfil(fullName, email);
} else {
Toast.makeText(CriarConta.this, "Erro: " + task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void salvarDadosNoPerfil(String fullName, String email) {
FirebaseUser firebaseUser = mAuth.getCurrentUser();
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
// Usamos o teu modelo User (Mapping: fullName -> name)
User user = new User(fullName, email);
mDatabase.child(userId).setValue(user)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(CriarConta.this, "Conta configurada com sucesso!", Toast.LENGTH_SHORT).show();
// Só avança se os dados foram salvos
Intent intent = new Intent(CriarConta.this, MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(CriarConta.this, "Erro ao salvar perfil no banco de dados.", Toast.LENGTH_SHORT).show();
}
});
}
}
} }

View File

@@ -1,11 +1,14 @@
package com.example.pap_findu; package com.example.pap_findu;
import android.content.Intent; import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.util.Base64;
import android.view.View; import android.view.View;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.ActivityResultLauncher;
@@ -15,9 +18,6 @@ import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide; import com.bumptech.glide.Glide;
import com.example.pap_findu.models.User; import com.example.pap_findu.models.User;
import com.example.pap_findu.ui.profile.ProfileFragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.button.MaterialButton; import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
@@ -27,25 +27,27 @@ import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener; import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference; import java.io.ByteArrayOutputStream;
import com.google.firebase.storage.UploadTask;
public class EditProfileActivity extends AppCompatActivity { public class EditProfileActivity extends AppCompatActivity {
private ImageView btnBack; private ImageView btnBack;
private ImageView editProfileImage; private ImageView editProfileImage;
private View btnChangePhoto; private TextView btnChangePhoto;
private TextInputEditText editName; private TextInputEditText editName;
private TextInputEditText editEmail; private TextInputEditText editEmail;
private TextInputEditText editPhone;
// Botoes
private MaterialButton btnSaveProfile; private MaterialButton btnSaveProfile;
private MaterialButton btnChangePassword;
private FirebaseAuth mAuth; private FirebaseAuth mAuth;
private DatabaseReference mDatabase; private DatabaseReference mDatabase;
private StorageReference mStorageRef;
private FirebaseUser currentUser; private FirebaseUser currentUser;
private Uri selectedImageUri;
// NOVO: Variável para guardar o texto gigante da imagem (Base64) em vez do Uri
private String base64ImageString = null;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@@ -55,7 +57,7 @@ public class EditProfileActivity extends AppCompatActivity {
mAuth = FirebaseAuth.getInstance(); mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser(); currentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference("users"); mDatabase = FirebaseDatabase.getInstance().getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference("profile_images"); // O StorageReference foi removido pois já não precisamos dele!
if (currentUser == null) { if (currentUser == null) {
finish(); finish();
@@ -73,8 +75,8 @@ public class EditProfileActivity extends AppCompatActivity {
btnChangePhoto = findViewById(R.id.btnChangePhoto); btnChangePhoto = findViewById(R.id.btnChangePhoto);
editName = findViewById(R.id.editName); editName = findViewById(R.id.editName);
editEmail = findViewById(R.id.editEmail); editEmail = findViewById(R.id.editEmail);
editPhone = findViewById(R.id.editPhone);
btnSaveProfile = findViewById(R.id.btnSaveProfile); btnSaveProfile = findViewById(R.id.btnSaveProfile);
btnChangePassword = findViewById(R.id.btnChangePassword);
} }
private void loadUserData() { private void loadUserData() {
@@ -85,13 +87,22 @@ public class EditProfileActivity extends AppCompatActivity {
if (user != null) { if (user != null) {
editName.setText(user.getName()); editName.setText(user.getName());
editEmail.setText(user.getEmail()); editEmail.setText(user.getEmail());
editPhone.setText(user.getPhone());
if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) { if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
Glide.with(EditProfileActivity.this) try {
.load(user.getProfileImageUrl()) // Tenta descodificar a imagem de formato Base64 (Texto para Imagem)
.placeholder(R.drawable.logo) byte[] decodedString = Base64.decode(user.getProfileImageUrl(), Base64.DEFAULT);
.into(editProfileImage); Glide.with(EditProfileActivity.this)
.load(decodedString)
.placeholder(R.drawable.logo)
.into(editProfileImage);
} catch (Exception e) {
// Se der erro (ex: se na DB estiver um link antigo em vez de Base64), tenta carregar normalmente
Glide.with(EditProfileActivity.this)
.load(user.getProfileImageUrl())
.placeholder(R.drawable.logo)
.into(editProfileImage);
}
} }
} else { } else {
// Fallback to auth data if DB is empty // Fallback to auth data if DB is empty
@@ -110,13 +121,26 @@ public class EditProfileActivity extends AppCompatActivity {
private void setupListeners() { private void setupListeners() {
btnBack.setOnClickListener(v -> finish()); btnBack.setOnClickListener(v -> finish());
// Lógica de mudar a senha
btnChangePassword.setOnClickListener(v -> {
String emailAddress = editEmail.getText().toString().trim();
if (!emailAddress.isEmpty()) {
enviarEmailRecuperacao(emailAddress);
} else {
Toast.makeText(this, "Erro: Email não encontrado.", Toast.LENGTH_SHORT).show();
}
});
// Image Picker Launcher // Image Picker Launcher
ActivityResultLauncher<Intent> imagePickerLauncher = registerForActivityResult( ActivityResultLauncher<Intent> imagePickerLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), new ActivityResultContracts.StartActivityForResult(),
result -> { result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) { if (result.getResultCode() == RESULT_OK && result.getData() != null) {
selectedImageUri = result.getData().getData(); Uri selectedImageUri = result.getData().getData();
editProfileImage.setImageURI(selectedImageUri); editProfileImage.setImageURI(selectedImageUri);
// NOVO: Faz a conversão mágica da imagem para texto!
converterImagemParaTexto(selectedImageUri);
} }
}); });
@@ -128,10 +152,41 @@ public class EditProfileActivity extends AppCompatActivity {
btnSaveProfile.setOnClickListener(v -> saveProfile()); btnSaveProfile.setOnClickListener(v -> saveProfile());
} }
// NOVO: Função que pega na foto, encolhe-a e transforma num texto gigante
private void converterImagemParaTexto(Uri imageUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
// Encolher para 300x300 pixeis para não exceder o limite da Realtime Database
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos); // Qualidade 70%
byte[] imageBytes = baos.toByteArray();
// Guarda a imagem final como uma string
base64ImageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Erro ao processar imagem", Toast.LENGTH_SHORT).show();
}
}
// Função para pedir ao Firebase para enviar email de reset
private void enviarEmailRecuperacao(String email) {
btnChangePassword.setEnabled(false);
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener(task -> {
btnChangePassword.setEnabled(true);
if (task.isSuccessful()) {
Toast.makeText(EditProfileActivity.this, "Email enviado! Verifique a sua caixa de entrada.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(EditProfileActivity.this, "Erro ao enviar email.", Toast.LENGTH_SHORT).show();
}
});
}
private void saveProfile() { private void saveProfile() {
String name = editName.getText().toString().trim(); String name = editName.getText().toString().trim();
String email = editEmail.getText().toString().trim(); String email = editEmail.getText().toString().trim();
String phone = editPhone.getText().toString().trim();
if (name.isEmpty() || email.isEmpty()) { if (name.isEmpty() || email.isEmpty()) {
Toast.makeText(this, "Nome e Email são obrigatórios", Toast.LENGTH_SHORT).show(); Toast.makeText(this, "Nome e Email são obrigatórios", Toast.LENGTH_SHORT).show();
@@ -139,32 +194,13 @@ public class EditProfileActivity extends AppCompatActivity {
} }
btnSaveProfile.setEnabled(false); btnSaveProfile.setEnabled(false);
btnSaveProfile.setText("Salvando..."); btnSaveProfile.setText("A Salvar...");
if (selectedImageUri != null) { // Guardamos o perfil passando a String Base64 (se houver), em vez de fazer upload para o Storage
uploadImageAndSaveUser(name, email, phone); saveUserToDb(name, email, base64ImageString);
} else {
saveUserToDb(name, email, phone, null);
}
} }
private void uploadImageAndSaveUser(String name, String email, String phone) { private void saveUserToDb(String name, String email, String imageUrlBase64) {
final StorageReference fileRef = mStorageRef.child(currentUser.getUid() + ".jpg");
fileRef.putFile(selectedImageUri)
.addOnSuccessListener(taskSnapshot -> fileRef.getDownloadUrl().addOnSuccessListener(uri -> {
String imageUrl = uri.toString();
saveUserToDb(name, email, phone, imageUrl);
}))
.addOnFailureListener(e -> {
Toast.makeText(EditProfileActivity.this, "Erro ao enviar imagem: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
btnSaveProfile.setEnabled(true);
btnSaveProfile.setText("Salvar Alterações");
});
}
private void saveUserToDb(String name, String email, String phone, String imageUrl) {
mDatabase.child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() { mDatabase.child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override @Override
public void onDataChange(@NonNull DataSnapshot snapshot) { public void onDataChange(@NonNull DataSnapshot snapshot) {
@@ -174,9 +210,10 @@ public class EditProfileActivity extends AppCompatActivity {
user.setName(name); user.setName(name);
user.setEmail(email); user.setEmail(email);
user.setPhone(phone);
if (imageUrl != null) { // Se houver uma imagem convertida em Base64, guardamos na base de dados
user.setProfileImageUrl(imageUrl); if (imageUrlBase64 != null) {
user.setProfileImageUrl(imageUrlBase64);
} }
mDatabase.child(currentUser.getUid()).setValue(user) mDatabase.child(currentUser.getUid()).setValue(user)

View File

@@ -1,18 +1,27 @@
package com.example.pap_findu; package com.example.pap_findu;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.location.Location;
import android.os.BatteryManager;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.app.Notification; import android.app.Notification;
import android.app.NotificationChannel; import android.app.NotificationChannel;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.Service; import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationCallback;
@@ -32,91 +41,112 @@ public class LocationService extends Service {
private LocationCallback locationCallback; private LocationCallback locationCallback;
private DatabaseReference databaseReference; private DatabaseReference databaseReference;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
// Inicializa o cliente de GPS e a ligação ao Firebase
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// ATENÇÃO: Substitua "ID_DA_CRIANCA" pelo ID real do utilizador logado no momento String childCode = getSharedPreferences("FindU_Prefs", MODE_PRIVATE)
databaseReference = FirebaseDatabase.getInstance().getReference("users/ID_DA_CRIANCA/live_location"); .getString("child_access_code", null);
if (childCode != null) {
// Caminho direto na raiz para o monitoramento em tempo real
databaseReference = FirebaseDatabase.getInstance().getReference(childCode).child("live_location");
}
} }
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
// 1. Inicia a Notificação Persistente (Obrigatório para serviços em background)
createNotificationChannel(); createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, "LocationChannel") Notification notification = new NotificationCompat.Builder(this, "LocationChannel")
.setContentTitle("FindU Ativo") .setContentTitle("FindU Ativo")
.setContentText("A monitorizar a localização em tempo real...") .setContentText("A partilhar localização e bateria em tempo real...")
// Substitua ic_launcher pelo ícone da sua app (ex: R.drawable.ic_launcher_foreground)
.setSmallIcon(R.mipmap.ic_launcher) .setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build(); .build();
startForeground(1, notification); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
} else {
startForeground(1, notification);
}
// 2. Inicia o Rastreamento de GPS if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
requestLocationUpdates(); requestLocationUpdates();
}
return START_STICKY; return START_STICKY;
} }
// Ignora o aviso de permissão porque vamos pedir a permissão na Activity ANTES de iniciar este serviço
@SuppressWarnings("MissingPermission")
private void requestLocationUpdates() { private void requestLocationUpdates() {
// Configura a frequência do GPS (ex: a cada 10 segundos) LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10000) .setMinUpdateDistanceMeters(0)
.setMinUpdateDistanceMeters(5.0f) // Só envia se a pessoa se mover 5 metros (poupa bateria)
.build(); .build();
locationCallback = new LocationCallback() { locationCallback = new LocationCallback() {
@Override @Override
public void onLocationResult(@NonNull LocationResult locationResult) { public void onLocationResult(@NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
for (Location location : locationResult.getLocations()) { for (Location location : locationResult.getLocations()) {
// Filtro para ignorar a localização padrão do emulador (Califórnia)
// 3. Envia os dados atualizados para o Firebase Realtime Database if (Math.abs(location.getLatitude() - 37.4219) > 0.001) {
Map<String, Object> locationData = new HashMap<>(); updateFirebase(location);
locationData.put("latitude", location.getLatitude()); }
locationData.put("longitude", location.getLongitude());
locationData.put("last_updated", System.currentTimeMillis());
databaseReference.setValue(locationData);
} }
} }
}; };
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()); try {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
} catch (SecurityException e) {
Log.e("LocationService", "Erro de permissão GPS");
}
}
private void updateFirebase(Location location) {
if (databaseReference != null) {
// --- LÓGICA DA BATERIA ---
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);
int level = -1;
if (batteryStatus != null) {
int rawLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
level = (int) ((rawLevel / (float) scale) * 100);
}
// -------------------------
Map<String, Object> data = new HashMap<>();
data.put("latitude", location.getLatitude());
data.put("longitude", location.getLongitude());
data.put("bateria", level + "%"); // Envia ex: "85%"
data.put("last_updated", System.currentTimeMillis());
databaseReference.setValue(data).addOnFailureListener(e -> {
Log.e("LocationService", "Erro ao enviar para Firebase: " + e.getMessage());
});
}
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
super.onDestroy();
// Quando o serviço for desligado, para de usar o GPS para poupar bateria
if (fusedLocationClient != null && locationCallback != null) { if (fusedLocationClient != null && locationCallback != null) {
fusedLocationClient.removeLocationUpdates(locationCallback); fusedLocationClient.removeLocationUpdates(locationCallback);
} }
super.onDestroy();
} }
// Cria o Canal de Notificação (obrigatório a partir do Android 8.0) @Nullable @Override public IBinder onBind(Intent intent) { return null; }
private void createNotificationChannel() { private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel( NotificationChannel channel = new NotificationChannel(
"LocationChannel", "LocationChannel",
"Monitoramento de Localização", "Monitoramento",
NotificationManager.IMPORTANCE_LOW // Low para não fazer barulho nem vibrar a toda a hora NotificationManager.IMPORTANCE_LOW
); );
NotificationManager manager = getSystemService(NotificationManager.class); NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) { if (manager != null) manager.createNotificationChannel(channel);
manager.createNotificationChannel(channel);
}
} }
} }
} }

View File

@@ -1,20 +1,45 @@
package com.example.pap_findu; package com.example.pap_findu;
import android.content.Intent; // <-- ADICIONADO import android.Manifest;
import android.os.Build; // <-- ADICIONADO import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController; import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI; import androidx.navigation.ui.NavigationUI;
import androidx.navigation.fragment.NavHostFragment;
import com.example.pap_findu.databinding.ActivityMainBinding; import com.example.pap_findu.databinding.ActivityMainBinding;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding; private ActivityMainBinding binding;
private FirebaseAuth mAuth;
private final ActivityResultLauncher<String[]> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissions -> {
Boolean fineLocationGranted = permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false);
if (fineLocationGranted != null && fineLocationGranted) {
decidirInicioDeServico();
} else {
Toast.makeText(this, "Sem permissão, o rastreamento não funcionará.", Toast.LENGTH_LONG).show();
}
});
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
@@ -23,8 +48,17 @@ public class MainActivity extends AppCompatActivity {
binding = ActivityMainBinding.inflate(getLayoutInflater()); binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot()); setContentView(binding.getRoot());
mAuth = FirebaseAuth.getInstance();
// Configuração da Navegação (Bottom Bar)
setupNavigation();
// Verifica permissões antes de tudo
checkAndRequestPermissions();
}
private void setupNavigation() {
BottomNavigationView navView = binding.navView; BottomNavigationView navView = binding.navView;
// Configurações da barra de navegação
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder( AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_map, R.id.navigation_zones, R.id.navigation_alerts, R.id.navigation_map, R.id.navigation_zones, R.id.navigation_alerts,
R.id.navigation_history, R.id.navigation_profile) R.id.navigation_history, R.id.navigation_profile)
@@ -36,20 +70,49 @@ public class MainActivity extends AppCompatActivity {
if (navHostFragment != null) { if (navHostFragment != null) {
NavController navController = navHostFragment.getNavController(); NavController navController = navHostFragment.getNavController();
NavigationUI.setupWithNavController(binding.navView, navController); NavigationUI.setupWithNavController(binding.navView, navController);
//teste }
}
private void checkAndRequestPermissions() {
List<String> permissionsNeeded = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
} }
// ======================================================== if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// CÓDIGO ADICIONADO: INICIAR O RASTREAMENTO EM BACKGROUND if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// ======================================================== permissionsNeeded.add(Manifest.permission.POST_NOTIFICATIONS);
Intent serviceIntent = new Intent(this, LocationService.class); }
}
// O Android 8.0 (Oreo) ou superior exige o startForegroundService if (!permissionsNeeded.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { requestPermissionLauncher.launch(permissionsNeeded.toArray(new String[0]));
startForegroundService(serviceIntent);
} else { } else {
startService(serviceIntent); decidirInicioDeServico();
} }
// ======================================================== }
// ========================================================
// LÓGICA DE DECISÃO: PAI VS FILHO
// ========================================================
private void decidirInicioDeServico() {
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.isAnonymous()) {
// É O FILHO: Precisamos de enviar a localização e bateria
startLocationService();
Log.d("MainActivity", "Modo Filho: Serviço de GPS iniciado.");
} else {
// É O PAI: Apenas carregamos a interface (o MapFragment tratará do resto)
Log.d("MainActivity", "Modo Pai: GPS desligado para poupar bateria.");
}
}
}
private void startLocationService() {
Intent serviceIntent = new Intent(this, LocationService.class);
ContextCompat.startForegroundService(this, serviceIntent);
} }
} }

View File

@@ -1,6 +1,7 @@
package com.example.pap_findu; package com.example.pap_findu;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.text.InputType; import android.text.InputType;
import android.text.TextUtils; import android.text.TextUtils;
@@ -25,10 +26,11 @@ import com.google.firebase.Timestamp;
import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestore;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class login_activity extends AppCompatActivity { public class login_activity extends AppCompatActivity {
@@ -37,7 +39,6 @@ public class login_activity extends AppCompatActivity {
private Button btnLogin; private Button btnLogin;
private TextView criarContaTextView; private TextView criarContaTextView;
// --- NOVAS VARIÁVEIS PARA O FILHO ---
private MaterialButton btnChildLogin; private MaterialButton btnChildLogin;
private FirebaseFirestore db; private FirebaseFirestore db;
private FirebaseAuth mAuth; private FirebaseAuth mAuth;
@@ -54,68 +55,46 @@ public class login_activity extends AppCompatActivity {
return insets; return insets;
}); });
// Inicializar Firebase Auth e Firestore
mAuth = FirebaseAuth.getInstance(); mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance(); db = FirebaseFirestore.getInstance();
// Vincular componentes
emailEditText = findViewById(R.id.emailEditText); emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText); passwordEditText = findViewById(R.id.passwordEditText);
btnLogin = findViewById(R.id.btnLogin); btnLogin = findViewById(R.id.btnLogin);
criarContaTextView = findViewById(R.id.criarContaTextView); criarContaTextView = findViewById(R.id.criarContaTextView);
// Novo botão do filho (Certifique-se que adicionou no XML com id btnChildLogin)
btnChildLogin = findViewById(R.id.btnChildLogin); btnChildLogin = findViewById(R.id.btnChildLogin);
// --- LÓGICA 1: LOGIN DO PAI (Seu código original) --- btnLogin.setOnClickListener(v -> {
btnLogin.setOnClickListener(new View.OnClickListener() { String email = emailEditText.getText().toString();
@Override String password = passwordEditText.getText().toString();
public void onClick(View v) {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (email.isEmpty() || password.isEmpty()) { if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(login_activity.this, "Por favor, preencha todos os campos.", Toast.LENGTH_SHORT).show(); Toast.makeText(login_activity.this, "Por favor, preencha todos os campos.", Toast.LENGTH_SHORT).show();
return; return;
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(login_activity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(login_activity.this, "Login com sucesso.", Toast.LENGTH_SHORT).show();
goToMainActivity();
} else {
Toast.makeText(login_activity.this, "Falha na autenticação.", Toast.LENGTH_SHORT).show();
}
}
});
} }
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(login_activity.this, task -> {
if (task.isSuccessful()) {
Toast.makeText(login_activity.this, "Login com sucesso.", Toast.LENGTH_SHORT).show();
goToMainActivity();
} else {
Toast.makeText(login_activity.this, "Falha na autenticação.", Toast.LENGTH_SHORT).show();
}
});
}); });
// --- LÓGICA 2: LOGIN DO FILHO (Novo código) --- btnChildLogin.setOnClickListener(v -> showChildLoginDialog());
btnChildLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showChildLoginDialog();
}
});
// --- LÓGICA 3: CRIAR CONTA --- criarContaTextView.setOnClickListener(v -> {
criarContaTextView.setOnClickListener(new View.OnClickListener() { Intent intent = new Intent(login_activity.this, CriarConta.class);
@Override startActivity(intent);
public void onClick(View v) {
Intent intent = new Intent(login_activity.this, CriarConta.class);
startActivity(intent);
}
}); });
} }
@Override @Override
public void onStart() { public void onStart() {
super.onStart(); super.onStart();
// Verifica se já está logado
FirebaseUser currentUser = mAuth.getCurrentUser(); FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){ if(currentUser != null){
goToMainActivity(); goToMainActivity();
@@ -124,28 +103,21 @@ public class login_activity extends AppCompatActivity {
private void goToMainActivity() { private void goToMainActivity() {
Intent intent = new Intent(login_activity.this, MainActivity.class); Intent intent = new Intent(login_activity.this, MainActivity.class);
// Limpa a pilha para não voltar ao login com o botão voltar
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent); startActivity(intent);
finish(); finish();
} }
// ==========================================================
// MÉTODOS DE LOGIN DO FILHO
// ==========================================================
private void showChildLoginDialog() { private void showChildLoginDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Acesso do Filho"); builder.setTitle("Acesso do Filho");
builder.setMessage("Digite o código de 6 dígitos gerado pelo pai:"); builder.setMessage("Digite o código de 6 dígitos gerado pelo pai:");
// Cria uma caixa de texto dentro do alerta
final EditText inputCode = new EditText(this); final EditText inputCode = new EditText(this);
inputCode.setInputType(InputType.TYPE_CLASS_NUMBER); inputCode.setInputType(InputType.TYPE_CLASS_NUMBER);
inputCode.setHint("Ex: 123456"); inputCode.setHint("Ex: 123456");
builder.setView(inputCode); builder.setView(inputCode);
// Botão Entrar do Alerta
builder.setPositiveButton("Entrar", (dialog, which) -> { builder.setPositiveButton("Entrar", (dialog, which) -> {
String code = inputCode.getText().toString().trim(); String code = inputCode.getText().toString().trim();
if (!TextUtils.isEmpty(code)) { if (!TextUtils.isEmpty(code)) {
@@ -160,14 +132,12 @@ public class login_activity extends AppCompatActivity {
} }
private void verifyChildCode(String code) { private void verifyChildCode(String code) {
// Verifica no Firestore se o código existe
db.collection("login_codes").document(code).get() db.collection("login_codes").document(code).get()
.addOnSuccessListener(document -> { .addOnSuccessListener(document -> {
if (document.exists()) { if (document.exists()) {
boolean used = Boolean.TRUE.equals(document.getBoolean("used")); boolean used = Boolean.TRUE.equals(document.getBoolean("used"));
Timestamp expiresAt = document.getTimestamp("expiresAt"); Timestamp expiresAt = document.getTimestamp("expiresAt");
// Validações
if (used) { if (used) {
Toast.makeText(this, "Este código já foi usado.", Toast.LENGTH_LONG).show(); Toast.makeText(this, "Este código já foi usado.", Toast.LENGTH_LONG).show();
return; return;
@@ -179,7 +149,20 @@ public class login_activity extends AppCompatActivity {
// SUCESSO: O código é bom! // SUCESSO: O código é bom!
String parentId = document.getString("parentId"); String parentId = document.getString("parentId");
loginChildAnonymously(code, parentId); String childName = document.getString("childName");
// =======================================================
// ASSOCIAÇÃO AUTOMÁTICA: Cria o registo na coleção 'children'
// =======================================================
Map<String, Object> childData = new HashMap<>();
childData.put("parentId", parentId);
childData.put("accessCode", code);
childData.put("name", childName != null ? childName : "Filho");
childData.put("createdAt", new Timestamp(new Date()));
db.collection("children").document(code).set(childData)
.addOnSuccessListener(aVoid -> loginChildAnonymously(code, parentId))
.addOnFailureListener(e -> Toast.makeText(this, "Erro ao associar filho.", Toast.LENGTH_SHORT).show());
} else { } else {
Toast.makeText(this, "Código inválido.", Toast.LENGTH_SHORT).show(); Toast.makeText(this, "Código inválido.", Toast.LENGTH_SHORT).show();
@@ -189,13 +172,18 @@ public class login_activity extends AppCompatActivity {
} }
private void loginChildAnonymously(String code, String parentId) { private void loginChildAnonymously(String code, String parentId) {
// Faz login anônimo (sem email)
mAuth.signInAnonymously() mAuth.signInAnonymously()
.addOnCompleteListener(this, task -> { .addOnCompleteListener(this, task -> {
if (task.isSuccessful()) { if (task.isSuccessful()) {
// 1. Invalida o código para ninguém usar de novo // Invalida o código no Firestore
db.collection("login_codes").document(code).update("used", true); db.collection("login_codes").document(code).update("used", true);
// Guarda o código para o LocationService usar
getSharedPreferences("FindU_Prefs", MODE_PRIVATE)
.edit()
.putString("child_access_code", code)
.apply();
Toast.makeText(this, "Conectado como Filho!", Toast.LENGTH_SHORT).show(); Toast.makeText(this, "Conectado como Filho!", Toast.LENGTH_SHORT).show();
goToMainActivity(); goToMainActivity();
} else { } else {

View File

@@ -2,24 +2,53 @@ package com.example.pap_findu.models;
public class ChatMessage { public class ChatMessage {
private String message; private String message;
private boolean isSentByMe; private String senderId;
private String timestamp; private String timestamp;
private boolean isSentByMe;
public ChatMessage(String message, boolean isSentByMe, String timestamp) { // 1. Construtor Vazio (OBRIGATÓRIO para o Firebase conseguir ler os dados)
public ChatMessage() {
}
// 2. Construtor para enviar mensagens (usado na ChatActivity)
public ChatMessage(String message, String senderId, String timestamp) {
this.message = message; this.message = message;
this.isSentByMe = isSentByMe; this.senderId = senderId;
this.timestamp = timestamp; this.timestamp = timestamp;
} }
// --- Getters e Setters ---
public String getMessage() { public String getMessage() {
return message; return message;
} }
public void setMessage(String message) {
this.message = message;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public boolean isSentByMe() { public boolean isSentByMe() {
return isSentByMe; return isSentByMe;
} }
public String getTimestamp() { // Este setter é usado na ChatActivity dentro do loop listenForMessages
return timestamp; public void setSentByMe(boolean sentByMe) {
isSentByMe = sentByMe;
} }
} }

View File

@@ -1,27 +1,47 @@
package com.example.pap_findu.ui.map; package com.example.pap_findu.ui.map;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.example.pap_findu.ChatActivity;
import com.example.pap_findu.R; import com.example.pap_findu.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
public class MapFragment extends Fragment { public class MapFragment extends Fragment implements OnMapReadyCallback {
private Button btnAddChild; private Button btnAddChild;
private View layoutEmptyState; private View layoutEmptyState;
@@ -29,28 +49,61 @@ public class MapFragment extends Fragment {
private FirebaseFirestore db; private FirebaseFirestore db;
private FirebaseAuth auth; private FirebaseAuth auth;
public View onCreateView(@NonNull LayoutInflater inflater, private FloatingActionButton btnAbrirChat;
ViewGroup container, Bundle savedInstanceState) { private MaterialButton btnSOS;
// --- VARIÁVEIS PARA O CARTÃO DE INFORMAÇÃO PREMIUM ---
private View cardChildInfo;
private TextView txtChildName;
private TextView txtChildBattery;
// --- VARIÁVEIS PARA A ZONA DE STATUS (VERDE/LARANJA) ---
private MaterialCardView cardZoneStatus, cardZoneIconBG;
private ImageView iconZone;
private TextView txtZoneTitle, txtZoneSubtitle;
private GoogleMap mMap;
private Marker childMarker;
private DatabaseReference locationRef;
private ValueEventListener locationListener;
private String currentChildId = null;
// NOVA VARIÁVEL: Guarda o nome real do filho
private String currentChildName = "A carregar...";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_map, container, false); View root = inflater.inflate(R.layout.fragment_map, container, false);
db = FirebaseFirestore.getInstance(); db = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance(); auth = FirebaseAuth.getInstance();
// Encontra os IDs no XML
layoutEmptyState = root.findViewById(R.id.layoutEmptyState); layoutEmptyState = root.findViewById(R.id.layoutEmptyState);
mapContainer = root.findViewById(R.id.mapContainer); mapContainer = root.findViewById(R.id.mapContainer);
btnAddChild = root.findViewById(R.id.btnAddChild); btnAddChild = root.findViewById(R.id.btnAddChild);
btnAbrirChat = root.findViewById(R.id.btnAbrirChat);
btnSOS = root.findViewById(R.id.btnSOS);
// --- INICIALIZAR AS VIEWS DO CARTÃO ---
cardChildInfo = root.findViewById(R.id.cardChildInfo);
txtChildName = root.findViewById(R.id.txtChildName);
txtChildBattery = root.findViewById(R.id.txtChildBattery);
// --- INICIALIZAR AS VIEWS DA ZONA ---
cardZoneStatus = root.findViewById(R.id.cardZoneStatus);
cardZoneIconBG = root.findViewById(R.id.cardZoneIconBG);
iconZone = root.findViewById(R.id.iconZone);
txtZoneTitle = root.findViewById(R.id.txtZoneTitle);
txtZoneSubtitle = root.findViewById(R.id.txtZoneSubtitle);
if (btnAbrirChat != null) btnAbrirChat.setVisibility(View.GONE);
if (btnSOS != null) btnSOS.setVisibility(View.GONE);
if (cardChildInfo != null) cardChildInfo.setVisibility(View.GONE); // Começa escondido
if (btnAddChild != null) { if (btnAddChild != null) {
btnAddChild.setOnClickListener(v -> { btnAddChild.setOnClickListener(v -> openAddChildScreen());
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
openAddChildScreen();
} else {
Toast.makeText(getContext(), "Erro: Utilizador não autenticado", Toast.LENGTH_SHORT).show();
}
});
} }
checkUserTypeAndShowScreen(); checkUserTypeAndShowScreen();
@@ -63,12 +116,11 @@ public class MapFragment extends Fragment {
if (user == null) return; if (user == null) return;
if (user.isAnonymous()) { if (user.isAnonymous()) {
if (btnAddChild != null) btnAddChild.setVisibility(View.GONE);
showMapState(); showMapState();
return; setupChildButtons();
} else {
checkIfHasChildren();
} }
checkIfHasChildren();
} }
private void checkIfHasChildren() { private void checkIfHasChildren() {
@@ -80,10 +132,27 @@ public class MapFragment extends Fragment {
.limit(1) .limit(1)
.get() .get()
.addOnCompleteListener(task -> { .addOnCompleteListener(task -> {
if (task.isSuccessful()) { if (task.isSuccessful() && task.getResult() != null && !task.getResult().isEmpty()) {
QuerySnapshot snapshot = task.getResult();
if (snapshot != null && !snapshot.isEmpty()) { // Extraímos o documento todo
DocumentSnapshot document = task.getResult().getDocuments().get(0);
currentChildId = document.getString("accessCode");
// LER O NOME REAL DA BASE DE DADOS FIRESTORE
if (document.contains("name")) {
currentChildName = document.getString("name");
} else if (document.contains("nome")) {
currentChildName = document.getString("nome");
} else {
currentChildName = "Filho";
}
if (currentChildId != null) {
showMapState(); showMapState();
setupChildButtons();
if (mMap != null) {
startListeningToChildLocation();
}
} else { } else {
showEmptyState(); showEmptyState();
} }
@@ -93,19 +162,141 @@ public class MapFragment extends Fragment {
}); });
} }
private void setupChildButtons() {
if (btnAbrirChat != null) {
btnAbrirChat.setVisibility(View.VISIBLE);
btnAbrirChat.setOnClickListener(v -> {
String roomCode = auth.getCurrentUser().isAnonymous() ?
requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE).getString("child_access_code", null) :
currentChildId;
if (roomCode != null) {
requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE).edit().putString("child_access_code", roomCode).apply();
startActivity(new Intent(getActivity(), ChatActivity.class));
}
});
}
if (btnSOS != null) btnSOS.setVisibility(View.VISIBLE);
}
private void showMapState() { private void showMapState() {
if (layoutEmptyState != null) layoutEmptyState.setVisibility(View.GONE); if (layoutEmptyState != null) layoutEmptyState.setVisibility(View.GONE);
if (mapContainer != null) mapContainer.setVisibility(View.VISIBLE); if (mapContainer != null) mapContainer.setVisibility(View.VISIBLE);
Fragment existingMap = getChildFragmentManager().findFragmentById(R.id.mapContainer); SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapContainer);
if (existingMap == null) { if (mapFragment != null) {
SupportMapFragment googleMapFragment = SupportMapFragment.newInstance(); mapFragment.getMapAsync(this);
getChildFragmentManager().beginTransaction()
.replace(R.id.mapContainer, googleMapFragment)
.commit();
} }
} }
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
FirebaseUser user = auth.getCurrentUser();
if (user != null && user.isAnonymous()) {
try { mMap.setMyLocationEnabled(true); } catch (SecurityException e) {}
} else {
if (currentChildId != null) {
startListeningToChildLocation();
} else {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(0, 0), 2f));
}
}
}
private void startListeningToChildLocation() {
if (currentChildId == null || mMap == null) return;
FirebaseUser user = auth.getCurrentUser();
// SE FOR O PAI, MOSTRAMOS O CARTÃO DO FILHO
if (user != null && !user.isAnonymous()) {
if (cardChildInfo != null) cardChildInfo.setVisibility(View.VISIBLE);
// CORREÇÃO: Agora usa estritamente o nome lido da base de dados (Ex: "Jorge")
if (txtChildName != null) {
txtChildName.setText(currentChildName);
}
}
locationRef = FirebaseDatabase.getInstance().getReference(currentChildId).child("live_location");
if (locationListener != null) locationRef.removeEventListener(locationListener);
locationListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists() && mMap != null) {
Double lat = snapshot.child("latitude").getValue(Double.class);
Double lng = snapshot.child("longitude").getValue(Double.class);
// LÊ A BATERIA DO FIREBASE
String bateria = snapshot.child("bateria").getValue(String.class);
// ATUALIZA O TEXTO DA BATERIA
if (bateria != null && txtChildBattery != null) {
txtChildBattery.setText(bateria);
}
if (lat != null && lng != null) {
LatLng childPos = new LatLng(lat, lng);
if (Math.abs(lat - 37.4219) > 0.001) {
if (childMarker == null) {
childMarker = mMap.addMarker(new MarkerOptions()
.position(childPos)
.title(currentChildName) // O pino no mapa também vai dizer o nome do filho
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
} else {
childMarker.setPosition(childPos);
childMarker.setTitle(currentChildName);
}
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(childPos, 17f));
// TESTE DE DESIGN
atualizarStatusZona(true, "A atualizar localização...");
}
}
}
}
@Override public void onCancelled(@NonNull DatabaseError error) {}
};
locationRef.addValueEventListener(locationListener);
}
// --- FUNÇÃO PARA MUDAR AS CORES DA ZONA (VERDE/LARANJA) ---
private void atualizarStatusZona(boolean naZonaSegura, String subtitulo) {
if (cardZoneStatus == null) return;
if (naZonaSegura) {
// MODO VERDE: Dentro de Zona Segura
cardZoneStatus.setCardBackgroundColor(Color.parseColor("#9DCA43"));
cardZoneIconBG.setCardBackgroundColor(Color.parseColor("#EAF4D4"));
iconZone.setColorFilter(Color.parseColor("#5F8B1A"));
txtZoneTitle.setText("Dentro de Zona Segura");
txtZoneTitle.setTextColor(Color.parseColor("#2D4608"));
txtZoneSubtitle.setText(subtitulo);
txtZoneSubtitle.setTextColor(Color.parseColor("#486B11"));
} else {
// MODO LARANJA: Em Movimento / Fora de Zonas
cardZoneStatus.setCardBackgroundColor(Color.parseColor("#FFA726"));
cardZoneIconBG.setCardBackgroundColor(Color.parseColor("#FFE0B2"));
iconZone.setColorFilter(Color.parseColor("#E65100"));
txtZoneTitle.setText("A movimentar-se");
txtZoneTitle.setTextColor(Color.parseColor("#822B00"));
txtZoneSubtitle.setText("Fora das zonas seguras");
txtZoneSubtitle.setTextColor(Color.parseColor("#A63A00"));
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (locationRef != null && locationListener != null) locationRef.removeEventListener(locationListener);
}
private void showEmptyState() { private void showEmptyState() {
if (layoutEmptyState != null) layoutEmptyState.setVisibility(View.VISIBLE); if (layoutEmptyState != null) layoutEmptyState.setVisibility(View.VISIBLE);
if (mapContainer != null) mapContainer.setVisibility(View.GONE); if (mapContainer != null) mapContainer.setVisibility(View.GONE);
@@ -113,40 +304,15 @@ public class MapFragment extends Fragment {
private void openAddChildScreen() { private void openAddChildScreen() {
AddChildBottomSheet bottomSheet = new AddChildBottomSheet(); AddChildBottomSheet bottomSheet = new AddChildBottomSheet();
bottomSheet.setListener(this::showCodeDialog);
bottomSheet.setListener(code -> {
// Quando o código é gerado, mostramos o diálogo de escolha
showCodeDialog(code);
});
bottomSheet.show(getParentFragmentManager(), "AddChildSheet"); bottomSheet.show(getParentFragmentManager(), "AddChildSheet");
} }
// --- AQUI ESTÁ A MUDANÇA PRINCIPAL ---
private void showCodeDialog(String code) { private void showCodeDialog(String code) {
if (getContext() == null) return; new AlertDialog.Builder(requireContext())
// 1. Copia o código automaticamente para a área de transferência
ClipboardManager clipboard = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Código", code);
clipboard.setPrimaryClip(clip);
Toast.makeText(getContext(), "Código copiado!", Toast.LENGTH_SHORT).show();
// 2. Cria o Alerta com as Duas Opções
new AlertDialog.Builder(getContext())
.setTitle("Filho Adicionado!") .setTitle("Filho Adicionado!")
.setMessage("O código de acesso é: " + code + "\n\n(Já copiado automaticamente)") .setMessage("Código: " + code)
.setCancelable(false) // Impede fechar clicando fora .setPositiveButton("OK", (d, w) -> checkIfHasChildren())
// OPÇÃO 1: Ir para o Mapa (Atualiza a tela)
.setPositiveButton("Ir para o Mapa", (dialog, which) -> {
checkIfHasChildren(); // <--- Esta função recarrega a tela e mostra o mapa
})
// OPÇÃO 2: Adicionar Outro (Fica na mesma tela)
.setNegativeButton("Adicionar Outro", (dialog, which) -> {
dialog.dismiss(); // Apenas fecha o alerta e continua na tela azul
})
.show(); .show();
} }
} }

View File

@@ -2,6 +2,7 @@ package com.example.pap_findu.ui.profile;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@@ -13,7 +14,6 @@ import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide; import com.bumptech.glide.Glide;
import com.example.pap_findu.EditProfileActivity; import com.example.pap_findu.EditProfileActivity;
import com.example.pap_findu.R; import com.example.pap_findu.R;
import com.example.pap_findu.SecurityActivity;
import com.example.pap_findu.databinding.FragmentProfileBinding; import com.example.pap_findu.databinding.FragmentProfileBinding;
import com.example.pap_findu.models.User; import com.example.pap_findu.models.User;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
@@ -28,12 +28,12 @@ public class ProfileFragment extends Fragment {
private FragmentProfileBinding binding; private FragmentProfileBinding binding;
private FirebaseAuth mAuth; private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
private ValueEventListener mUserListener;
private DatabaseReference mUserRef; private DatabaseReference mUserRef;
private ValueEventListener mUserListener;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) { ViewGroup container, Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false); binding = FragmentProfileBinding.inflate(inflater, container, false);
View root = binding.getRoot(); View root = binding.getRoot();
@@ -41,49 +41,68 @@ public class ProfileFragment extends Fragment {
FirebaseUser currentUser = mAuth.getCurrentUser(); FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) { if (currentUser == null) {
// Should prompt login or handle error
return root; return root;
} }
mDatabase = FirebaseDatabase.getInstance().getReference("users");
mUserRef = mDatabase.child(currentUser.getUid());
setupListeners(); setupListeners();
// Listen for user data changes // Verifica se é o Filho (Anónimo)
mUserListener = new ValueEventListener() { if (currentUser.isAnonymous()) {
@Override binding.profileName.setText("Conta de Criança");
public void onDataChange(@NonNull DataSnapshot snapshot) { binding.profileEmail.setText("Modo de Monitorização Ativo");
if (getContext() == null) binding.profileImage.setImageResource(R.drawable.logo);
return;
User user = snapshot.getValue(User.class); // Oculta opções que não fazem sentido para o Filho
if (user != null) { binding.layoutEditProfile.setVisibility(View.GONE);
binding.profileName.setText(user.getName());
binding.profileEmail.setText(user.getEmail());
if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) { } else {
Glide.with(ProfileFragment.this) // É O PAI: Carrega os dados reais do Firebase
.load(user.getProfileImageUrl()) mUserRef = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
.placeholder(R.drawable.logo) // Make sure logo exists or use R.mipmap.ic_launcher
.into(binding.profileImage); mUserListener = new ValueEventListener() {
} else { @Override
binding.profileImage.setImageResource(R.drawable.logo); public void onDataChange(@NonNull DataSnapshot snapshot) {
if (getContext() == null || binding == null) return;
if (snapshot.exists()) {
User user = snapshot.getValue(User.class);
if (user != null) {
binding.profileName.setText(user.getName());
binding.profileEmail.setText(user.getEmail());
// MAGIA: LER A FOTO EM FORMATO DE TEXTO (BASE64)
if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
try {
byte[] decodedString = Base64.decode(user.getProfileImageUrl(), Base64.DEFAULT);
Glide.with(ProfileFragment.this)
.load(decodedString)
.placeholder(R.drawable.logo)
.into(binding.profileImage);
} catch (Exception e) {
// Fallback caso a imagem seja um link antigo e não Base64
try {
Glide.with(ProfileFragment.this)
.load(user.getProfileImageUrl())
.placeholder(R.drawable.logo)
.into(binding.profileImage);
} catch (Exception ex) {
binding.profileImage.setImageResource(R.drawable.logo);
}
}
} else {
binding.profileImage.setImageResource(R.drawable.logo);
}
}
} }
} else {
// Fallback to Auth data if DB is empty
binding.profileName.setText(
currentUser.getDisplayName() != null ? currentUser.getDisplayName() : "Utilizador");
binding.profileEmail.setText(currentUser.getEmail());
} }
}
@Override @Override
public void onCancelled(@NonNull DatabaseError error) { public void onCancelled(@NonNull DatabaseError error) {
if (getContext() != null) if (getContext() != null)
Toast.makeText(getContext(), "Erro ao carregar perfil", Toast.LENGTH_SHORT).show(); Toast.makeText(getContext(), "Erro ao carregar perfil", Toast.LENGTH_SHORT).show();
} }
}; };
}
return root; return root;
} }
@@ -93,10 +112,6 @@ public class ProfileFragment extends Fragment {
startActivity(new Intent(getActivity(), EditProfileActivity.class)); startActivity(new Intent(getActivity(), EditProfileActivity.class));
}); });
binding.layoutSecurity.setOnClickListener(v -> {
startActivity(new Intent(getActivity(), SecurityActivity.class));
});
binding.btnLogout.setOnClickListener(v -> { binding.btnLogout.setOnClickListener(v -> {
mAuth.signOut(); mAuth.signOut();
Intent intent = new Intent(getActivity(), com.example.pap_findu.login_activity.class); Intent intent = new Intent(getActivity(), com.example.pap_findu.login_activity.class);

View File

@@ -9,7 +9,6 @@
android:background="#F6F7FB" android:background="#F6F7FB"
tools:context=".EditProfileActivity"> tools:context=".EditProfileActivity">
<!-- Header -->
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
@@ -48,7 +47,6 @@
android:padding="24dp" android:padding="24dp"
android:gravity="center_horizontal"> android:gravity="center_horizontal">
<!-- Profile Image -->
<FrameLayout <FrameLayout
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content"> android:layout_height="wrap_content">
@@ -62,32 +60,35 @@
app:shapeAppearanceOverlay="@style/ShapeAppearance.MaterialComponents.MediumComponent" app:shapeAppearanceOverlay="@style/ShapeAppearance.MaterialComponents.MediumComponent"
android:src="@drawable/logo" /> android:src="@drawable/logo" />
<ImageView <com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="32dp" android:layout_width="wrap_content"
android:layout_height="32dp" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_gravity="bottom|end"
android:background="@drawable/bg_circle_button" android:layout_marginEnd="-8dp"
android:padding="6dp" android:layout_marginBottom="-8dp"
android:src="@android:drawable/ic_menu_camera" android:src="@android:drawable/ic_menu_camera"
app:tint="#FFFFFF" /> app:backgroundTint="#3B82F6"
app:fabSize="mini"
app:tint="#FFFFFF"
android:clickable="false" />
</FrameLayout> </FrameLayout>
<TextView <TextView
android:id="@+id/btnChangePhoto" android:id="@+id/btnChangePhoto"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="8dp" android:layout_marginTop="16dp"
android:text="Alterar Foto" android:text="Alterar Foto"
android:textColor="#3B82F6" android:textColor="#3B82F6"
android:textStyle="bold" android:textStyle="bold"
android:clickable="true" android:clickable="true"
android:padding="8dp"
android:background="?attr/selectableItemBackground" /> android:background="?attr/selectableItemBackground" />
<!-- Form -->
<com.google.android.material.textfield.TextInputLayout <com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="32dp" android:layout_marginTop="24dp"
android:hint="Nome Completo" android:hint="Nome Completo"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"> style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
@@ -102,35 +103,34 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:layout_marginTop="16dp"
android:hint="Email" android:hint="Email (Não editável)"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"> style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText <com.google.android.material.textfield.TextInputEditText
android:id="@+id/editEmail" android:id="@+id/editEmail"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:inputType="textEmailAddress" /> android:inputType="textEmailAddress"
android:enabled="false"
android:textColor="#9CA3AF"/>
</com.google.android.material.textfield.TextInputLayout> </com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout <com.google.android.material.button.MaterialButton
android:id="@+id/btnChangePassword"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="56dp"
android:layout_marginTop="16dp" android:layout_marginTop="24dp"
android:hint="Telefone (Opcional)" android:text="MUDAR PALAVRA-PASSE"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"> android:textColor="#3B82F6"
app:strokeColor="#3B82F6"
<com.google.android.material.textfield.TextInputEditText app:cornerRadius="12dp" />
android:id="@+id/editPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton <com.google.android.material.button.MaterialButton
android:id="@+id/btnSaveProfile" android:id="@+id/btnSaveProfile"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="60dp" android:layout_height="60dp"
android:layout_marginTop="40dp" android:layout_marginTop="32dp"
android:text="Salvar Alterações" android:text="Salvar Alterações"
app:cornerRadius="12dp" /> app:cornerRadius="12dp" />

View File

@@ -5,128 +5,264 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="#F3F6FB"> tools:context=".ui.map.MapFragment">
<androidx.constraintlayout.widget.ConstraintLayout <LinearLayout
android:id="@+id/layoutEmptyState" android:id="@+id/layoutEmptyState"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:visibility="visible"> android:gravity="center"
android:orientation="vertical"
<View android:visibility="gone">
android:id="@+id/viewHeader"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="@drawable/bg_header_rounded"
app:layout_constraintTop_toTopOf="parent" />
<TextView <TextView
android:id="@+id/tvAppTitle"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="24dp" android:text="Ainda não tem filhos associados."
android:text="FindU" android:textSize="18sp"
android:textColor="@android:color/white" android:layout_marginBottom="16dp"/>
android:textSize="22sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.cardview.widget.CardView <Button
android:id="@+id/cardEmptyState" android:id="@+id/btnAddChild"
android:layout_width="match_parent" android:layout_width="wrap_content"
android:layout_height="0dp" android:layout_height="wrap_content"
android:layout_marginHorizontal="24dp" android:text="Adicionar Filho" />
android:layout_marginTop="30dp" </LinearLayout>
android:layout_marginBottom="24dp"
app:cardCornerRadius="20dp"
app:cardElevation="4dp"
app:layout_constraintBottom_toTopOf="@+id/btnSOS"
app:layout_constraintTop_toBottomOf="@+id/tvAppTitle">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp">
<View
android:id="@+id/bgIcon"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/bg_circle_light_blue"
app:layout_constraintBottom_toTopOf="@+id/tvNoChildTitle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@android:drawable/ic_menu_add"
app:layout_constraintBottom_toBottomOf="@+id/bgIcon"
app:layout_constraintEnd_toEndOf="@+id/bgIcon"
app:layout_constraintStart_toStartOf="@+id/bgIcon"
app:layout_constraintTop_toTopOf="@+id/bgIcon"
app:tint="#3D6DFF" />
<TextView
android:id="@+id/tvNoChildTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Nenhum filho adicionado"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/tvNoChildDesc"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/bgIcon" />
<TextView
android:id="@+id/tvNoChildDesc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="Adicione o seu primeiro filho para começar."
app:layout_constraintBottom_toTopOf="@+id/btnAddChild"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvNoChildTitle" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnAddChild"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Adicionar Filho"
android:textStyle="bold"
app:backgroundTint="#3D6DFF"
app:cornerRadius="12dp"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<com.google.android.material.button.MaterialButton
android:id="@+id/btnSOS"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_marginHorizontal="24dp"
android:layout_marginBottom="24dp"
android:text="SOS"
app:backgroundTint="#D32F2F"
app:cornerRadius="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.fragment.app.FragmentContainerView <androidx.fragment.app.FragmentContainerView
android:id="@+id/mapContainer" android:id="@+id/mapContainer"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardChildInfo"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="wrap_content"
android:visibility="gone" /> android:layout_marginHorizontal="20dp"
android:layout_marginTop="32dp"
app:cardCornerRadius="24dp"
app:cardElevation="8dp"
app:cardBackgroundColor="#FFFFFF"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<com.google.android.material.card.MaterialCardView
android:layout_width="56dp"
android:layout_height="56dp"
app:cardCornerRadius="28dp"
app:cardBackgroundColor="#F0F4FF"
app:cardElevation="0dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp"
android:src="@android:drawable/ic_menu_myplaces"
app:tint="#A0AABF"/>
</com.google.android.material.card.MaterialCardView>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="16dp">
<TextView
android:id="@+id/txtChildName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nome do Filho"
android:textColor="#1F2937"
android:textSize="20sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="2dp">
<com.google.android.material.card.MaterialCardView
android:layout_width="10dp"
android:layout_height="10dp"
app:cardCornerRadius="5dp"
app:cardBackgroundColor="#4CAF50"
app:cardElevation="0dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Online"
android:textColor="#4CAF50"
android:textStyle="bold"
android:textSize="14sp"
android:layout_marginStart="6dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="end">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:src="@android:drawable/ic_lock_idle_charging"
app:tint="#4CAF50"/>
<TextView
android:id="@+id/txtChildBattery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="--%"
android:textColor="#1F2937"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginStart="4dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="6dp">
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:src="@android:drawable/ic_menu_mylocation"
app:tint="#3B82F6"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS"
android:textColor="#1F2937"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginStart="4dp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardZoneStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="12dp"
app:cardBackgroundColor="#9DCA43"
app:cardElevation="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="12dp"
android:gravity="center_vertical">
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardZoneIconBG"
android:layout_width="36dp"
android:layout_height="36dp"
app:cardCornerRadius="18dp"
app:cardBackgroundColor="#EAF4D4"
app:cardElevation="0dp">
<ImageView
android:id="@+id/iconZone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:src="@android:drawable/ic_menu_mylocation"
app:tint="#5F8B1A"/>
</com.google.android.material.card.MaterialCardView>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="12dp">
<TextView
android:id="@+id/txtZoneTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dentro de Zona Segura"
android:textColor="#2D4608"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/txtZoneSubtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A carregar..."
android:textColor="#486B11"
android:textSize="13sp"/>
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/btnAbrirChat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:backgroundTint="#4CAF50"
app:tint="@android:color/white"
android:src="@android:drawable/ic_dialog_email"
app:layout_constraintBottom_toTopOf="@+id/btnSOS"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnSOS"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
android:text="BOTÃO SOS DE EMERGÊNCIA"
android:textColor="@android:color/white"
android:textSize="16sp"
android:textStyle="bold"
app:backgroundTint="#D32F2F"
app:cornerRadius="12dp"
app:icon="@android:drawable/ic_menu_call"
app:iconGravity="textEnd"
app:iconPadding="16dp"
app:iconTint="@android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -60,7 +60,6 @@
</LinearLayout> </LinearLayout>
</FrameLayout> </FrameLayout>
<!-- Account Settings Section -->
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
@@ -88,7 +87,6 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical"> android:orientation="vertical">
<!-- Item 1 -->
<LinearLayout <LinearLayout
android:id="@+id/layoutEditProfile" android:id="@+id/layoutEditProfile"
android:layout_width="match_parent" android:layout_width="match_parent"
@@ -121,47 +119,9 @@
android:rotation="0" /> android:rotation="0" />
</LinearLayout> </LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#F3F4F6" />
<!-- Item 2 -->
<LinearLayout
android:id="@+id/layoutSecurity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:gravity="center_vertical"
android:padding="16dp">
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@android:drawable/ic_lock_idle_lock"
app:tint="#4B5563" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:text="Segurança e Senha"
android:textColor="#1F2937"
android:textSize="16sp" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@android:drawable/ic_media_play"
app:tint="#9CA3AF"
android:rotation="0" />
</LinearLayout>
</LinearLayout> </LinearLayout>
</com.google.android.material.card.MaterialCardView> </com.google.android.material.card.MaterialCardView>
<!-- App Settings Section -->
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
@@ -189,7 +149,6 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical"> android:orientation="vertical">
<!-- Item 1 -->
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
@@ -224,7 +183,6 @@
android:layout_height="1dp" android:layout_height="1dp"
android:background="#F3F4F6" /> android:background="#F3F4F6" />
<!-- Item 2 -->
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
@@ -274,7 +232,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="8dp" android:layout_marginTop="8dp"
android:gravity="center" android:gravity="center"
android:text="FindU Inc. © 2024" android:text="FindU Inc. © 2026"
android:textColor="#D1D5DB" android:textColor="#D1D5DB"
android:textSize="12sp" /> android:textSize="12sp" />