MonoDroid学习笔记(十一)—— 使用SQLiteOpenHelper实现简易备忘录

不管是做winform的还是web的,都难免要和数据库打交道。这次我们就来探讨一下如何在MonoDroid里使用手机上的Portable数据库SQLite。数据库不外乎就是CRUD(增删改查)操作,我们来设计一个简单的数据库来放置备忘录,提醒用户还有哪些工作事项。

我们使用Menu来做数据库的增,改,删,同时搭配ListView用以查处已经增加的记录,用一个EditText作为新增或修改的录入框。

[xhtml]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.                 android:layout_width="fill_parent"  
  4.                 android:layout_height="fill_parent">  
  5.   <TextView android:id="@+id/tvInfo"  
  6.             android:text="按MENU可新增、修改、删除"  
  7.             android:layout_width="fill_parent"  
  8.             android:layout_height="wrap_content"/>  
  9.   <EditText android:id="@+id/txtInfo"  
  10.             android:layout_width="fill_parent"  
  11.             android:layout_height="wrap_content"  
  12.             android:layout_below="@id/tvInfo"/>  
  13.   <ListView android:id="@+id/lvInfo"  
  14.             android:layout_width="fill_parent"  
  15.             android:layout_height="fill_parent"  
  16.             android:layout_below="@id/txtInfo">  
  17.   </ListView>  
  18. </RelativeLayout>  
 

在Layout目录下新建一个ListItem.axml布局文件,用于ListView中的项的布局:

[xhtml]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent" android:layout_height="wrap_content">  
  5.   <TextView android:id="@+id/txtView"  
  6.               android:layout_width="fill_parent"  
  7.               android:layout_height="wrap_content"/>  
  8. </LinearLayout>  
 

为了创建及访问数据库,我们新建一个类MySQLiteHelper,继承SQLiteOpenHelper抽象类,重写OnCreate及OnUpgrade方法,当数据库创建时,会调用OnCreate,所以可将要添加的数据库表写在里面。当更新数据库时,会调用OnUpgrade,所以可将要更新表的sql语句写在里面,同时增加增、删、改、查四个方法以供外部调用:

[c-sharp]  view plain copy print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Android.App;  
  6. using Android.Content;  
  7. using Android.OS;  
  8. using Android.Runtime;  
  9. using Android.Views;  
  10. using Android.Widget;  
  11. namespace MonoDroidTest  
  12. {  
  13.     public class MySQLiteHelper : Android.Database.Sqlite.SQLiteOpenHelper  
  14.     {  
  15.         //调用基类的构造函数,数据库名称起为MemoDb  
  16.         public MySQLiteHelper(Context context)  
  17.             : base(context, "MemoDb"null, 1)  
  18.         {  
  19.         }  
  20.         //在OnCreate中新建数据库表Memo,有_id字段及memoinfo字段  
  21.         public override void OnCreate(Android.Database.Sqlite.SQLiteDatabase db)  
  22.         {  
  23.             string sql = "create table Memo(_id integer primary key autoincrement, memoinfo text)";  
  24.             db.ExecSQL(sql);  
  25.         }  
  26.         //更新数据库时先将Memo删除再重新创建  
  27.         public override void OnUpgrade(Android.Database.Sqlite.SQLiteDatabase db, int oldVersion, int newVersion)  
  28.         {  
  29.             string sql = "drop table if exists Memo";  
  30.             db.ExecSQL(sql);  
  31.             OnCreate(db);  
  32.         }  
  33.         //查出Memo表中的数据  
  34.         public Android.Database.ICursor Select()  
  35.         {  
  36.             return this.ReadableDatabase.Query("Memo"nullnullnullnullnullnull);  
  37.         }  
  38.         //向Memo中插入一条新数据  
  39.         public long Insert(string info)  
  40.         {  
  41.             ContentValues values = new ContentValues();  
  42.             values.Put("memoinfo", info);  
  43.             return this.ReadableDatabase.Insert("Memo"null, values);  
  44.         }  
  45.         //删除Memo中一条记录  
  46.         public void Delete(int id)  
  47.         {  
  48.             this.ReadableDatabase.Delete("Memo""_id=?"new string[] { id.ToString() });  
  49.         }  
  50.         //根据id修改Memo的记录  
  51.         public void Update(int id, string info)  
  52.         {  
  53.             ContentValues values = new ContentValues();  
  54.             values.Put("memoinfo", info);  
  55.             this.ReadableDatabase.Update("Memo", values, "_id=?"new string[] { id.ToString() });  
  56.         }  
  57.     }  
  58. }  
 

 

在Activity1中添加三个menu作为新增,修改和删除,在Menu的点击选择事件ItemSelected中调用MySQLiteHelper来访问数据库,当单击ListView时,可将选择的数据带入上方的EditText做修改,做完增删改操作后,立即更新下方的ListView。若EditText里的值为空时,则不添加到数据库。

[c-sharp]  view plain copy print ?
  1. [Activity(Label = "MonoDroidTest", MainLauncher = true)]  
  2. public class Activity1 : Activity  
  3. {  
  4.     int id;  
  5.     ListView lvInfo;  
  6.     EditText txtInfo;  
  7.     MySQLiteHelper db;  
  8.     ICursor cur;  
  9.     protected override void OnCreate(Bundle bundle)  
  10.     {  
  11.         base.OnCreate(bundle);  
  12.         SetContentView(Resource.Layout.Main);  
  13.         try  
  14.         {  
  15.             lvInfo = FindViewById<ListView>(Resource.Id.lvInfo);  
  16.             txtInfo = FindViewById<EditText>(Resource.Id.txtInfo);  
  17.             db = new MySQLiteHelper(this);  
  18.             cur = db.Select();  
  19.             SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, Resource.Layout.ListItem, cur, new string[] { "memoinfo" }, new int[] { Resource.Id.txtView });  
  20.             lvInfo.Adapter = adapter;  
  21.             lvInfo.ItemClick += (sender, e) =>  
  22.             {  
  23.                 cur.MoveToPosition(e.Position);  
  24.                 id = cur.GetInt(0);  
  25.                 txtInfo.Text = cur.GetString(1);  
  26.             };  
  27.             lvInfo.ItemSelected += (sender, e) =>  
  28.             {  
  29.                 SQLiteCursor sc = (sender as AdapterView).SelectedItem as SQLiteCursor;  
  30.                 id = sc.GetInt(0);  
  31.                 txtInfo.Text = sc.GetString(1);  
  32.             };  
  33.         }  
  34.         catch (System.Exception ex)  
  35.         {  
  36.             MessageBox.ShowErrorMessage(this, ex);  
  37.         }  
  38.     }  
  39.     private const int NONE = MenuConsts.None;  
  40.     private const int MENU_ADD = MenuConsts.First;  
  41.     private const int MENU_EDIT = MenuConsts.First + 1;  
  42.     private const int MENU_DELETE = MenuConsts.First + 2;  
  43.     public override bool OnCreateOptionsMenu(IMenu menu)  
  44.     {  
  45.         menu.Add(NONE, MENU_ADD, 0, new Java.Lang.String("新增"));  
  46.         menu.Add(NONE, MENU_EDIT, 1, new Java.Lang.String("修改"));  
  47.         menu.Add(NONE, MENU_DELETE, 2, new Java.Lang.String("删除"));  
  48.         return base.OnCreateOptionsMenu(menu);  
  49.     }  
  50.     public override bool OnOptionsItemSelected(IMenuItem item)  
  51.     {  
  52.         bool b = base.OnOptionsItemSelected(item);  
  53.         switch (item.ItemId)  
  54.         {  
  55.             case MENU_ADD:  
  56.                 Add();  
  57.                 break;  
  58.             case MENU_EDIT:  
  59.                 Edit();  
  60.                 break;  
  61.             case MENU_DELETE:  
  62.                 Delete();  
  63.                 break;  
  64.         }  
  65.         return b;  
  66.     }  
  67.     private void Add()  
  68.     {  
  69.         if (string.IsNullOrEmpty(txtInfo.Text))  
  70.             return;  
  71.         db.Insert(txtInfo.Text);  
  72.         Init();  
  73.     }  
  74.     private void Edit()  
  75.     {  
  76.         if (string.IsNullOrEmpty(txtInfo.Text) || id == 0)  
  77.             return;  
  78.         try  
  79.         {  
  80.             db.Update(id, txtInfo.Text);  
  81.             Init();  
  82.         }  
  83.         catch (System.Exception ex)  
  84.         {  
  85.             MessageBox.ShowErrorMessage(this, ex);  
  86.         }  
  87.     }  
  88.     private void Delete()  
  89.     {  
  90.         if (id == 0)  
  91.             return;  
  92.         db.Delete(id);  
  93.         Init();  
  94.     }  
  95.     private void Init()  
  96.     {  
  97.         cur.Requery();  
  98.         lvInfo.InvalidateViews();  
  99.         txtInfo.Text = "";  
  100.         id = 0;  
  101.     }  
  102. }  
 

使用SimpleCursorAdapter来做ListView的adapter,将Cursor及要显示的字段名称传入,就会产生想要显示的数据的ListView。另外值得注意的一点是,使用SimpleCursorAdapter所设计的数据表一定要有_id这个字段名称,否则会抛出“找不到_id字段”的异常。

MonoDroid学习笔记(十一)—— 使用SQLiteOpenHelper实现简易备忘录

转载http://blog.csdn.net/ojlovecd/article/details/6337008

你可能感兴趣的:(sqlite)