sqlite maui

main
syneffort 1 year ago
parent b07b1ace6e
commit 96ba5a0216
  1. 8
      MyFirstMauiApp/LocalDataStorageWithSQLite/MainPage.xaml.cs
  2. 20
      MyFirstMauiApp/LocalDataStorageWithSQLite/Repositories/PersonRepository.cs

@ -26,19 +26,19 @@ namespace LocalDataStorageWithSQLite
//int a = 0; //int a = 0;
} }
public void OnNewButtonClicked(object sender, EventArgs args) public async void OnNewButtonClicked(object sender, EventArgs args)
{ {
statusMessage.Text = ""; statusMessage.Text = "";
App.PersonRepo.AddNewPerson(newPerson.Text); await App.PersonRepo.AddNewPerson(newPerson.Text);
statusMessage.Text = App.PersonRepo.StatusMessage; statusMessage.Text = App.PersonRepo.StatusMessage;
} }
public void OnGetButtonClicked(object sender, EventArgs args) public async void OnGetButtonClicked(object sender, EventArgs args)
{ {
statusMessage.Text = ""; statusMessage.Text = "";
List<Person> people = App.PersonRepo.GetAllPeople(); List<Person> people = await App.PersonRepo.GetAllPeople();
peopleList.ItemsSource = people; peopleList.ItemsSource = people;
} }
} }

@ -16,14 +16,14 @@ namespace LocalDataStorageWithSQLite.Repositories
// TODO: Add variable for the SQLite connection // TODO: Add variable for the SQLite connection
private SQLiteConnection _conn; private SQLiteAsyncConnection _conn;
private void Init() private async Task Init()
{ {
if (_conn != null) if (_conn != null)
return; return;
_conn = new SQLiteConnection(_dbPath); _conn = new SQLiteAsyncConnection(_dbPath);
_conn.CreateTable<Person>(); await _conn.CreateTableAsync<Person>();
} }
public PersonRepository(string dbPath) public PersonRepository(string dbPath)
@ -31,17 +31,17 @@ namespace LocalDataStorageWithSQLite.Repositories
_dbPath = dbPath; _dbPath = dbPath;
} }
public void AddNewPerson(string name) public async Task AddNewPerson(string name)
{ {
int result = 0; int result = 0;
try try
{ {
Init(); await Init();
if (string.IsNullOrEmpty(name)) if (string.IsNullOrEmpty(name))
throw new Exception("Valid name required"); throw new Exception("Valid name required");
result = _conn.Insert(new Person { Name = name }); result = await _conn.InsertAsync(new Person { Name = name });
StatusMessage = string.Format("{0} record(s) added (Name: {1})", result, name); StatusMessage = string.Format("{0} record(s) added (Name: {1})", result, name);
} }
@ -52,12 +52,12 @@ namespace LocalDataStorageWithSQLite.Repositories
} }
public List<Person> GetAllPeople() public async Task<List<Person>> GetAllPeople()
{ {
try try
{ {
Init(); await Init();
return _conn.Table<Person>().ToList(); return await _conn.Table<Person>().ToListAsync();
} }
catch (Exception ex) catch (Exception ex)
{ {

Loading…
Cancel
Save