首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步SQLite示例与dot42?

异步SQLite示例与dot42?
EN

Stack Overflow用户
提问于 2013-11-08 20:20:47
回答 1查看 446关注 0票数 2

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

有什么建议吗?

提前感谢

罗加

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-11 11:37:42

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

代码语言:javascript
复制
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);
         }
      }
   }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19867847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档