Saving and Deleting Items

After some thought I’ve decided to add or remove items from the SQLite database as soon as they’re added to either list or removed from the Add list (the other option I entertained was replacing the entire database contents with the entire allItems list in memory when the app went to the background or was closed).

The work took less than half an hour. First I added the appropriate AddItem and RemoveItem methods to the ItemDatabase class. In each method I called the appropriate SQLite data connection method to insert or delete the item record.

public void AddItem(Item item)
{
	database.Insert(item);
}

public void RemoveItem(Item item)
{
	database.Delete<Item>(item.ID);
}

I called the AddItem method in the OnSaveClicked handler in AddItemPage.xaml.cs.

void OnSaveClicked(object sender, EventArgs args)
{
	bool itemAlreadyExists = false;

	if (Application.Current.Properties.ContainsKey("Items")) {
		allItems = (List<Item>)Application.Current.Properties["Items"];

		Item newItem = new Item(itemEntry.Text, addToBuyList);
		itemAlreadyExists = CheckListForExistingItem(newItem);

		if (itemAlreadyExists) {
			DisplayAlert("Duplicate Item", "This item already exists in one of your lists.", "OK");
		} else {
			allItems.Add(newItem);
			itemEntry.Text = "";

			// Add item to database
			App.Database.AddItem(newItem);

			if (!addToBuyList) MessagingCenter.Send<AddItemPage>(this, "UpdateAddItemsListFromAddItems");
			else MessagingCenter.Send<AddItemPage>(this, "UpdateBuyItemsListFromAddItems");
		}
	}
}

And the RemoveItem method in the AddPage.cs’s RemoveItem.

internal void RemoveItem(AddCell item)
{
	Item itemToRemove = null;

	if (Application.Current.Properties.ContainsKey("Items")) {
		allItems = (List<Item>)Application.Current.Properties["Items"];
		itemToRemove = allItems.First(x => x.Name == item.Text);
		allItems.Remove(itemToRemove);
	}

	// Remove item from database
	App.Database.RemoveItem(itemToRemove);

	addView.ItemsSource = UpdateAddItemsList();
}

Some helpful links during development:

This entry was posted in Side Projects, Software Development and tagged , , , , . Bookmark the permalink.