Asynchronous SQLite sample with dot42?

风流意气都作罢 提交于 2019-12-11 02:45:29

问题


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


回答1:


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);
         }
      }
   }
}


来源:https://stackoverflow.com/questions/19867847/asynchronous-sqlite-sample-with-dot42

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!