Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Intent 做一個能用的記事本:SQLite 加 ListView 完整實作

編輯:關於 Android 程式設計

本文示範如何用 Intent 串起一個簡單的記事本(NotePad)應用,包含清單顯示、新增、編輯與刪除。

一、成品預覽

點擊右上角選單可新增;長按任一筆記錄會彈出情境選單提供刪除。

二、建置步驟

1. 加入 SQLite 參考

在「參考」上按右鍵選擇「加入參考」,勾選 System.Data 與 System.Data.SQLite。

注意:不需要透過 NuGet 安裝 SQLite 套件,用這種方式加入即可。

2. 加入圖示資源

從 Android SDK API 23 的 NotePad 範例中找到 app_notes.png,加入專案後更名為 ch12_app_notes.png。

3. 編輯器版面

這裡用了一個自訂的 LinedEditText,讓輸入框帶有橫線,比較像真的筆記紙:

<?xml version="1.0" encoding="utf-8"?>
<view xmlns:android="https://schemas.android.com/apk/res/android"
    class="MyDemos.SrcDemos.ch1205LinedEditText"
    android:id="@+id/note"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dip"
    android:scrollbars="vertical"
    android:fadingEdge="vertical"
    android:gravity="top"
    android:textSize="22sp"
    android:capitalize="sentences" />

4. 清單項版面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="#ffffff"
    android:padding="10px">
    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ch12_app_notes" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="6px">
        <TextView
            android:id="@+id/body"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/modified"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

5. 資料模型

class ch1205Note : Java.Lang.Object {
    public long Id { get; set; }
    public string Body { get; set; }
    public DateTime ModifiedTime { get; set; }

    public ch1205Note() {
        Id = -1L;
        Body = string.Empty;
    }

    public ch1205Note(long id, string body, DateTime modified) {
        Id = id;
        Body = body;
        ModifiedTime = modified;
    }

    public override string ToString() {
        return ModifiedTime.ToString();
    }
}

Id 初始化為 -1 是個刻意的設計:後續用來判斷「這是一筆新記錄還是既有記錄」,決定要執行 INSERT 還是 UPDATE。

6. 帶橫線的 EditText

[Register("MyDemos.SrcDemos.ch1205LinedEditText")]
class ch1205LinedEditText : EditText {
    private Rect rect;
    private Paint paint;

    // LayoutInflater 需要這個建構子
    public ch1205LinedEditText(Context context, IAttributeSet attrs)
            : base(context, attrs) {
        rect = new Rect();
        paint = new Paint();
        paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
        paint.Color = Color.LightGray;
    }

    protected override void OnDraw(Canvas canvas) {
        int count = LineCount;
        for (int i = 0; i < count; i++) {
            int baseline = GetLineBounds(i, rect);
            canvas.DrawLine(rect.Left, baseline + 1, rect.Right, baseline + 1, paint);
        }
        base.OnDraw(canvas);
    }
}

關鍵是 GetLineBounds:它回傳每一行的基線位置,讓我們能把橫線畫在文字下方,而不是硬編碼行高。

7. 資料存取層

class ch1205NoteRepository {

    private static string db_file = "notes.db3";

    private static SqliteConnection GetConnection() {
        var dbPath = System.IO.Path.Combine(
            System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal), db_file);
        bool exists = System.IO.File.Exists(dbPath);
        if (!exists) SqliteConnection.CreateFile(dbPath);

        var conn = new SqliteConnection("Data Source=" + dbPath);
        if (!exists) CreateDatabase(conn);
        return conn;
    }

    private static void CreateDatabase(SqliteConnection connection) {
        var sql = "CREATE TABLE ITEMS (Id INTEGER PRIMARY KEY AUTOINCREMENT, Body ntext, Modified datetime);";
        connection.Open();
        using (var cmd = connection.CreateCommand()) {
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
        }
        // 建立一筆範例資料讓使用者有東西可看
        sql = "INSERT INTO ITEMS (Body, Modified) VALUES (@Body, @Modified);";
        using (var cmd = connection.CreateCommand()) {
            cmd.CommandText = sql;
            cmd.Parameters.AddWithValue("@Body", "今天有個約會");
            cmd.Parameters.AddWithValue("@Modified", DateTime.Now);
            cmd.ExecuteNonQuery();
        }
        connection.Close();
    }

    public static IEnumerable<ch1205Note> GetAllNotes() {
        var sql = "SELECT * FROM ITEMS;";
        using (var conn = GetConnection()) {
            conn.Open();
            using (var cmd = conn.CreateCommand()) {
                cmd.CommandText = sql;
                using (var reader = cmd.ExecuteReader()) {
                    while (reader.Read()) {
                        yield return new ch1205Note(
                            reader.GetInt32(0),
                            reader.GetString(1),
                            reader.GetDateTime(2));
                    }
                }
            }
        }
    }

    public static ch1205Note GetNote(long id) {
        var sql = "SELECT * FROM ITEMS WHERE Id = id;";
        using (var conn = GetConnection()) {
            conn.Open();
            using (var cmd = conn.CreateCommand()) {
                cmd.CommandText = sql;
                using (var reader = cmd.ExecuteReader()) {
                    if (reader.Read())
                        return new ch1205Note(reader.GetInt32(0),
                                reader.GetString(1), reader.GetDateTime(2));
                    return null;
                }
            }
        }
    }

    public static void DeleteNote(ch1205Note note) {
        var sql = string.Format("DELETE FROM ITEMS WHERE Id = {0};", note.Id);
        using (var conn = GetConnection()) {
            conn.Open();
            using (var cmd = conn.CreateCommand()) {
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            }
        }
    }

    public static void SaveNote(ch1205Note note) {
        using (var conn = GetConnection()) {
            conn.Open();
            using (var cmd = conn.CreateCommand()) {
                if (note.Id < 0) {
                    // 新記錄:INSERT 後取回自動產生的主鍵
                    cmd.CommandText = "INSERT INTO ITEMS (Body, Modified) VALUES (@Body, @Modified); SELECT last_insert_rowid();";
                    cmd.Parameters.AddWithValue("@Body", note.Body);
                    cmd.Parameters.AddWithValue("@Modified", DateTime.Now);
                    note.Id = (long)cmd.ExecuteScalar();
                } else {
                    // 既有記錄:UPDATE
                    cmd.CommandText = "UPDATE ITEMS SET Body = @Body, Modified = @Modified WHERE Id = @Id";
                    cmd.Parameters.AddWithValue("@Id", note.Id);
                    cmd.Parameters.AddWithValue("@Body", note.Body);
                    cmd.Parameters.AddWithValue("@Modified", DateTime.Now);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

這裡有個實務上值得注意的細節:資料庫位置放在 SpecialFolder.Personal,也就是 App 的私有目錄,不需要額外申請外部儲存權限。

8. Adapter

class ch1205NoteAdapter : ArrayAdapter {

    private Activity activity;

    public ch1205NoteAdapter(Activity activity, Context context,
                             int textViewResourceId, ch1205Note[] objects)
            : base(context, textViewResourceId, objects) {
        this.activity = activity;
    }

    public override Android.Views.View GetView(int position,
            Android.Views.View convertView, Android.Views.ViewGroup parent) {
        var item = (ch1205Note)GetItem(position);
        // convertView 不為 null 就重複使用,避免每次都重新 inflate
        var view = (convertView
                ?? activity.LayoutInflater.Inflate(
                        Resource.Layout.ch1205_Main, parent, false)) as LinearLayout;
        view.FindViewById<TextView>(Resource.Id.body).Text =
                Left(item.Body.Replace("\n", " "), 25);
        view.FindViewById<TextView>(Resource.Id.modified).Text =
                item.ModifiedTime.ToString();
        return view;
    }

    private string Left(string text, int length) {
        if (text.Length <= length) return text;
        return text.Substring(0, length);
    }
}

9. 編輯用的 Activity

[Activity(Label = "ch1205NoteEditorActivity",
    ScreenOrientation = ScreenOrientation.Sensor,
    ConfigurationChanges = ConfigChanges.KeyboardHidden | ConfigChanges.Orientation)]
public class ch1205NoteEditorActivity : Activity {

    private ch1205Note note;
    private EditText text_view;

    protected override void OnCreate(Bundle savedInstanceState) {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ch1205_NoteEditor);
        text_view = FindViewById<EditText>(Resource.Id.note);

        var note_id = Intent.GetLongExtra("note_id", -1L);
        if (note_id < 0)
            note = new ch1205Note();   // 新增
        else
            note = ch1205NoteRepository.GetNote(note_id); // 編輯
    }

    protected override void OnResume() {
        base.OnResume();
        text_view.SetTextKeepState(note.Body);
    }

    protected override void OnPause() {
        base.OnPause();
        // 新增的空白記事本不存檔,直接返回
        if (IsFinishing && note.Id == -1 && text_view.Text.Length == 0) return;
        note.Body = text_view.Text;
        ch1205NoteRepository.SaveNote(note);
    }
}

存檔時機選在 OnPause 而非「儲存」按鈕,是 Android 開發的慣例做法——使用者可能隨時按首頁鍵離開,不能假設他一定會點某個按鈕。

10. 主畫面

[Activity(Label = "ch1205NotePadMain")]
public class ch1205NotePadMain : ListActivity {

    public const int MenuItemDelete = Menu.First;
    public const int MenuItemInsert = Menu.First + 1;

    protected override void OnCreate(Bundle savedInstanceState) {
        base.OnCreate(savedInstanceState);
        SetDefaultKeyMode(DefaultKey.Shortcut);
        ListView.SetOnCreateContextMenuListener(this);
        PopulateList();
    }

    public void PopulateList() {
        var notes = ch1205NoteRepository.GetAllNotes();
        ListAdapter = new ch1205NoteAdapter(this, this,
                Resource.Layout.ch1205_Main, notes.ToArray());
    }

    public override bool OnCreateOptionsMenu(IMenu menu) {
        base.OnCreateOptionsMenu(menu);
        menu.Add(0, MenuItemInsert, 0, "添加")
            .SetShortcut('3', 'a')
            .SetIcon(Android.Resource.Drawable.IcMenuAdd);
        return true;
    }

    public override bool OnOptionsItemSelected(IMenuItem item) {
        switch (item.ItemId) {
            case MenuItemInsert:
                var intent = new Intent(this, typeof(ch1205NoteEditorActivity));
                intent.PutExtra("note_id", -1L); // -1 代表新增
                StartActivityForResult(intent, 0);
                return true;
        }
        return base.OnOptionsItemSelected(item);
    }

    public override void OnCreateContextMenu(IContextMenu menu, View view,
                                            IContextMenuContextMenuInfo menuInfo) {
        var info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.Add(0, MenuItemDelete, 0, "刪除");
    }

    public override bool OnContextItemSelected(IMenuItem item) {
        var info = (AdapterView.AdapterContextMenuInfo)item.MenuInfo;
        var note = (ch1205Note)ListAdapter.GetItem(info.Position);
        switch (item.ItemId) {
            case MenuItemDelete:
                ch1205NoteRepository.DeleteNote(note);
                PopulateList();
                return true;
        }
        return false;
    }

    protected override void OnListItemClick(ListView l, View v, int position, long id) {
        var selected = (ch1205Note)ListAdapter.GetItem(position);
        var intent = new Intent(this, typeof(ch1205NoteEditorActivity));
        intent.PutExtra("note_id", selected.Id);
        StartActivityForResult(intent, 0);
    }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) {
        base.OnActivityResult(requestCode, resultCode, data);
        // 不處理選中項,重點是回來時刷新清單
        PopulateList();
    }
}

整個流程的骨幹其實就是 Intent 的兩種用法:用 PutExtra 傳遞 note_id 前來區分新增與編輯,用 StartActivityForResult 搭配 OnActivityResult 在返回時刷新清單。這兩個模式在幾乎所有「列表 + 詳情」型的 App 裡都會用到。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved