【问题标题】:Asynchronous SQLite sample with dot42?带有dot42的异步SQLite示例?
【发布时间】:2013-11-20 23:33:48
【问题描述】:

我一直在测试 dot42,到目前为止还不错,但我发现没有任何 SQLite 示例。我不确定我是否应该实现 ContentProvider(正如一些 android 文章所建议的那样),或者我是否可以使用 dot42 的 async / wait 实现来异步执行查询并在 ListView 上显示结果。

有什么建议吗?

提前致谢

罗伊加

【问题讨论】:

    标签: dot42


    【解决方案1】:

    这是一个代码示例,它使用 dot42 的 async/await 实现从 SQLite 数据库异步检索联系人。我省略了 SQLite 代码。 ContactsDatabase 继承自 SQLiteOpenHelper 并实现常用方法。

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

    【讨论】:

    • 感谢您的回答
    • 不客气。如果您认为它回答了您的问题,您可能希望接受该答案。
    猜你喜欢
    • 2018-01-29
    • 2017-10-26
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多