Search code examples
dot42

Asynchronous SQLite sample with dot42?


I've been testing dot42 and so far great, but I see that there aren't any SQLite samples. Im not sure if I should implement a ContentProvider (as some android articles suggests) or if I could use the async / wait implementation of dot42 in order to perform a query asynchronously and show the result on a ListView.

Any advice ?

Thanks in advance

Roygar


Solution

  • Here is a code sample that retrieves contacts from a SQLite database asynchronously using the async/await implementation of dot42. I omitted the SQLite code. ContactsDatabase inherits from SQLiteOpenHelper and implements the usual methods.

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    
    using Android.App;
    using Android.Os;
    using Android.Widget;
    
    using Dot42;
    using Dot42.Manifest;
    
    [assembly: Application("SQLiteAsyncSample")]
    
    namespace SQLiteAsyncSample
    {
       [Activity]
       public class MainActivity : Activity
       {
          private ArrayAdapter<string> adapter;
          ContactsDatabase database;
          int i = 0;
    
          protected override void OnCreate(Bundle savedInstance)
          {
             base.OnCreate(savedInstance);
             SetContentView(R.Layouts.MainLayout);
    
             ListView list = FindViewById<ListView>(R.Ids.list);
             adapter = new ArrayAdapter<string>(this, Android.R.Layout.Simple_list_item_1);
             list.SetAdapter(adapter);
    
             database = new ContactsDatabase(this);
    
             database.AddContact(new Contact("Frank", "012"));
             database.AddContact(new Contact("Marco", "345"));
             database.AddContact(new Contact("Hans", "678"));
             database.AddContact(new Contact("Sergey", "901"));
    
             Button addAllButton = FindViewById<Button>(R.Ids.showall);
             addAllButton.Click += showAllButton_Click;
    
             // Set the static synchronization context to the current/latest 'this'.
             // This allows the code after the wait to resume on the 'current' this
             // even if the Activity was recycled, e.g. due to a device rotation.
             SynchronizationContext.SetSynchronizationContext(this);
          }
    
          private async void showAllButton_Click(object sender, EventArgs e)
          {
             List<Contact> contacts = null;
             await Task.Factory.StartNew( () => {
                // lengthy job
                contacts = database.GetAllContacts();
             }).ConfigureAwait(this);
    
             // make sure to access the adapter from the UI thread
             // so not in the anonymous delegate above
             foreach (Contact contact in contacts) {
                adapter.Add(contact.Name);
             }
          }
       }
    }