You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
Seekers/Views/AddContactPage.xaml.cs

113 lines
3.7 KiB

using Justice.Helpers;
using Justice.Models;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
namespace Justice.Views
{
public partial class AddContactPage : ContentPage
{
private readonly DatabaseHelper _databaseHelper;
public ObservableCollection<EmergencyContact> Contacts { get; set; }
public AddContactPage()
{
InitializeComponent();
_databaseHelper = new DatabaseHelper();
Contacts = new ObservableCollection<EmergencyContact>();
ContactsListView.ItemsSource = Contacts;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await LoadContactsAsync();
}
private async Task LoadContactsAsync()
{
try
{
Contacts.Clear();
var contactsFromDb = await _databaseHelper.GetAllAsync<EmergencyContact>();
foreach (var contact in contactsFromDb)
{
Contacts.Add(contact);
}
}
catch (Exception ex)
{
await DisplayAlert("Error", $"Failed to load contacts: {ex.Message}", "OK");
}
}
private async void OnSaveContactClicked(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(NameEntry.Text) ||
string.IsNullOrWhiteSpace(MobileNumberEntry.Text) ||
GroupPicker.SelectedItem == null)
{
await DisplayAlert("Error", "All fields are required.", "OK");
return;
}
var contact = new EmergencyContact
{
Name = NameEntry.Text.Trim(),
MobileNumber = MobileNumberEntry.Text.Trim(),
Group = GroupPicker.SelectedItem.ToString()
};
try
{
await _databaseHelper.InsertAsync(contact);
await LoadContactsAsync();
NameEntry.Text = string.Empty;
MobileNumberEntry.Text = string.Empty;
GroupPicker.SelectedItem = null;
await DisplayAlert("Success", "Contact saved successfully!", "OK");
}
catch (Exception ex)
{
await DisplayAlert("Error", $"Failed to save contact: {ex.Message}", "OK");
}
}
private async void OnDeleteContactClicked(object sender, EventArgs e)
{
try
{
Console.WriteLine("Delete button clicked."); // Debug log
var button = sender as Button;
if (button?.CommandParameter is EmergencyContact contactToDelete)
{
Console.WriteLine($"Attempting to delete contact: {contactToDelete.Name}"); // Debug log
bool confirm = await DisplayAlert("Delete Contact",
$"Are you sure you want to delete {contactToDelete.Name}?", "Yes", "No");
if (!confirm)
return;
await _databaseHelper.DeleteAsync(contactToDelete);
Contacts.Remove(contactToDelete);
await DisplayAlert("Success", "Contact deleted successfully!", "OK");
}
else
{
Console.WriteLine("CommandParameter is null or invalid."); // Debug log
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in OnDeleteContactClicked: {ex.Message}"); // Debug log
await DisplayAlert("Error", $"Failed to delete contact: {ex.Message}", "OK");
}
}
}
}