Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 個人理財實作之三:新增帳單頁面的資料層設計(上)

編輯:Android 開發實例

ColaBox 的記帳功能走到這一步,終於要面對真正的硬骨頭了。新增帳單這個畫面,我翻了不少資料,最後乾脆把 Android 原始碼打開來讀,才總算把它做出來——那一刻才真正體會到 Google 選擇開源是多麼明智的決定。

從登入畫面到記帳畫面

使用者通過登入頁之後,便會跳轉到新增帳單頁。顧名思義,這個頁面的工作就是把一筆一筆的收支明細寫進資料庫,說白了就是往表裡 insert 資料。

對應的資料表結構如下:

db.execSQL("CREATE TABLE bills ("
    + "_ID INTEGER PRIMARY KEY,"   // 主鍵
    + "fee integer,"               // 費用金額
    + "acctitemid integer,"        // 帳目類型
    + "userid integer,"            // 使用者
    + "sdate TEXT,"                // 日期
    + "stime TEXT,"                // 時間
    + "desc TEXT"                  // 備註
    + ");");

要錄入的欄位大致就是這些。第一步先把版面排出來,我當時選用 TableLayout 來做整體佈局。

最終的排版結果如下圖(圖 1):

帳目選擇:為什麼不用 Dialog

首先要處理的是「帳目」欄位。前面幾篇已經把帳目資料初始化好了,這裡要做的只是把它讀出來攤在畫面上。

帳目本身是個兩層結構(大類底下掛細項),最自然的做法就是 ExpandableListActivity,資料則直接從資料庫查詢。我在帳目欄位後面放了一個只讀、沒有游標的 EditText,讓它不能輸入文字,改而在它的 onClick 事件裡開啟帳目選擇畫面,如下圖:

圖 2 帳目選擇:

點擊子節點後即返回前一頁,並把選中的帳目名稱一併帶回來。

但這裡有個現實問題:如果使用者要記的帳目清單裡根本沒有,那該怎麼辦?

正是因為這個顧慮,我沒有採用 Dialog 方案,而是直接用 ExpandableListActivity。在這個畫面裡,只要長按某個子節點,就會弹出帳目管理選單,讓使用者自行維護帳目,如下圖所示:

圖 3 帳目選擇選單:

圖 4 編輯帳目:

這些流程講起來輕描淡寫,真要動手寫卻處處是坑。好在一個一個都解掉了,而這也正是寫程式最有趣的地方。

用 SimpleCursorTreeAdapter 撑起兩層 Tree

關於 ExpandableListActivity,可以參考 Android SDK 裡 apidemos 的 ExpandableList1、ExpandableList2、ExpandableList3 三個範例,對熟悉這個 UI 幫助很大。其中 ExpandableList2 就是「從資料庫讀取」的示範。

不過 Android 官方那個範例我當初沒看太懂,因為它 import 了 android.provider.Contacts.People,走的是聯絡人 Provider 的路子;而我自己的做法比較直接,全部用 SQL 存取。

但其實只要搞定兩個 Cursor 就行了——groupCursor 與 childCursor,剩下的 (SimpleCursorTreeAdapter) 會幫你補完。

// 父節點游標,等同 select * from acctitem where pid is null
Cursor groupCursor = billdb.getParentNode();

// 快取 ID 欄位的索引
mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow("_ID");

// 建立 adapter,父子層都套用系統內建的 simple_expandable_list_item_1
mAdapter = new MyExpandableListAdapter(
        groupCursor, this,
        android.R.layout.simple_expandable_list_item_1,
        android.R.layout.simple_expandable_list_item_1,
        new String[] { "NAME" }, new int[] { android.R.id.text1 },
        new String[] { "NAME" }, new int[] { android.R.id.text1 });

setListAdapter(mAdapter);

// 子節點游標,等同 select * from acctitem where pid = ?
public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {

    public MyExpandableListAdapter(Cursor cursor, Context context,
            int groupLayout, int childLayout,
            String[] groupFrom, int[] groupTo,
            String[] childrenFrom, int[] childrenTo) {
        super(context, cursor, groupLayout, groupFrom, groupTo,
                childLayout, childrenFrom, childrenTo);
    }

    @Override
    protected Cursor getChildrenCursor(Cursor groupCursor) {
        String pid = groupCursor.getLong(mGroupIdColumnIndex) + "";
        return billdb.getChildenNode(pid);
    }
}

對應到 BilldbHelper 裡的兩個查詢方法:

public Cursor getParentNode() {
    return db.query("acctitem", new String[] { "_id", "name" },
            "pid is null", null, null, null, "pid,_id");
}

public Cursor getChildenNode(String pid) {
    return db.query("acctitem", new String[] { "_id", "name" },
            "pid=" + pid, null, null, null, "_id");
}

就這幾步,一個兩層的 tree list 便成形了。

自訂 Dialog:讓使用者能輸入帳目名稱

上面其實只是開場。接下來還需要一個自訂的 Dialog,類似一個 inputBox,因為新增帳目時必須讓使用者輸入名稱,也就是圖 4 的樣子。

AlertDialog 雖然提供了不少現成方法,可以選 list、treelist、radio,偏偏就是沒法直接錄入 text。

這裡我參考了 apidemos 裡的 DateWidgets1.java,以及原始碼中的 DatePickerDialog.java。做法很直接:從 AlertDialog 繼承,塞一個 EditText 進去,再把結果透過回呼傳出來。把這兩個檔案讀通之後,實作起來就沒什麼難度了,關鍵在於回呼函數的用法。

public class Dialog_edit extends AlertDialog implements OnClickListener {

    private String text = "";
    private EditText edit;
    private OnDateSetListener mCallback;   // 回呼函數
    private LinearLayout layout;

    public interface OnDateSetListener {   // 回呼介面
        void onDateSet(String text);
    }

    protected Dialog_edit(Context context, String title, String value,
            OnDateSetListener Callback) {
        super(context);
        mCallback = Callback;

        edit = new EditText(context);
        edit.setText(value);

        layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(edit, new LinearLayout.LayoutParams(200, 50));

        setView(layout);
        setTitle(title);
        setButton("確定", this);
        setButton2("取消", (OnClickListener) null);
    }

    public void onClick(DialogInterface dialog, int which) {
        text = edit.getText().toString();
        if (mCallback != null) {
            mCallback.onDateSet(text);     // 用回呼把輸入的資料送出去
        }
    }
}

這樣自訂對話框就完成了,新增與編輯帳目都能共用它。至於帳目的增刪改,剩下的就只是 SQL 的事。

改完之後,畫面怎麼刷新?

接著又踩到一個坑:新增一筆帳目之後,如何刷新畫面讓它反映最新狀態?

一開始我以為 getExpandableListView().invalidate() 就夠了——畢竟在 ExpandableList1.java 那個範例裡,我改完陣列再呼叫它,畫面確實就更新了。但換到 SimpleCursorTreeAdapter 這裡卻行不通。

想想也合理:既然資料來源是 Cursor,那應該刷新 Cursor 才對。後來找到 notifyDataSetChanged,果然一試就通了。

private void updatedisplay() {
    ((MyExpandableListAdapter) mAdapter).notifyDataSetChanged();
}

至此,帳目的錄入與管理都搞定了。下面是目前最新的幾段關鍵程式碼。

帳目管理:Frm_Editacctitem 的核心邏輯

public class Frm_Editacctitem extends ExpandableListActivity {

    private int mGroupIdColumnIndex;
    private ExpandableListAdapter mAdapter;
    private BilldbHelper billdb;
    private Dialog_edit newdialog;
    private ExpandableListContextMenuInfo info;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("ColaBox-選擇帳目");
        billdb = new BilldbHelper(this);

        Cursor groupCursor = billdb.getParentNode();
        mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow("_ID");

        mAdapter = new MyExpandableListAdapter(groupCursor, this,
                android.R.layout.simple_expandable_list_item_1,
                android.R.layout.simple_expandable_list_item_1,
                new String[] { "NAME" }, new int[] { android.R.id.text1 },
                new String[] { "NAME" }, new int[] { android.R.id.text1 });

        setListAdapter(mAdapter);
        registerForContextMenu(getExpandableListView());
    }

    // 點本子節點:把名稱塞進 Intent 回傳,然後關掉自己
    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
            int groupPosition, int childPosition, long id) {
        Bundle bundle = new Bundle();
        bundle.putString("DataKey", ((TextView) v).getText().toString());
        Intent mIntent = new Intent();
        mIntent.putExtras(bundle);
        setResult(RESULT_OK, mIntent);
        billdb.close();
        finish();
        return true;
    }

    // 只有子節點才顯示管理選單(packedPosition type == 1 代表 child)
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateOptionsMenu(menu);
        if (ExpandableListView
                .getPackedPositionType(((ExpandableListContextMenuInfo) menuInfo).packedPosition) == 1) {
            menu.setHeaderTitle("選單");
            menu.add(0, 1, 0, "新 增");
            menu.add(0, 2, 0, "刪 除");
            menu.add(0, 3, 0, "編 輯");
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        info = (ExpandableListContextMenuInfo) item.getMenuInfo();

        if (item.getItemId() == 1) {          // 新增
            newdialog = new Dialog_edit(this, "請輸入新增帳目的名稱", "",
                    mDialogClick_new);
            newdialog.show();
        } else if (item.getItemId() == 2) {   // 刪除(先二次確認)
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("確定要刪除'" + ((TextView) info.targetView).getText()
                            + "'這個帳目嗎?")
                    .setIcon(R.drawable.quit)
                    .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            billdb.Acctitem_delitem((int) info.id);
                            updatedisplay();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // 取消,不做任何事
                        }
                    }).show();
        } else if (item.getItemId() == 3) {   // 編輯
            newdialog = new Dialog_edit(this, "請修改帳目名稱",
                    ((TextView) info.targetView).getText().toString(),
                    mDialogClick_edit);
            newdialog.show();
        }
        return false;
    }

    private Dialog_edit.OnDateSetListener mDialogClick_new =
            new Dialog_edit.OnDateSetListener() {
        public void onDateSet(String text) {
            billdb.Acctitem_newitem(text,
                    ExpandableListView.getPackedPositionGroup(info.packedPosition));
            updatedisplay();
        }
    };

    private Dialog_edit.OnDateSetListener mDialogClick_edit =
            new Dialog_edit.OnDateSetListener() {
        public void onDateSet(String text) {
            billdb.Acctitem_edititem(text, (int) info.id);
            updatedisplay();
        }
    };
}

資料庫層:BilldbHelper 的帳目相關方法

public class BilldbHelper {

    private static final String TAG = "Cola_BilldbHelper";
    private static final String DATABASE_NAME = "cola.db";

    SQLiteDatabase db;
    Context context;

    BilldbHelper(Context _context) {
        context = _context;
        db = context.openOrCreateDatabase(DATABASE_NAME, 0, null);
        Log.v(TAG, "db path=" + db.getPath());
    }

    public void CreateTable_acctitem() {
        try {
            db.execSQL("CREATE TABLE acctitem ("
                    + "_ID INTEGER PRIMARY KEY,"
                    + "PID integer,"
                    + "NAME TEXT"
                    + ");");
        } catch (Exception e) {
            Log.v("cola", "Create Table acctitem err, table exists.");
        }
    }

    // 新增:在 9998 以前取 max(_id)+1 當新 id
    public void Acctitem_newitem(String text, int type) {
        Cursor c = db.query("acctitem", new String[] { "max(_id)+1" },
                "_id is not null and _id<9998", null, null, null, null);
        c.moveToFirst();
        int maxid = c.getInt(0);
        db.execSQL("insert into acctitem values (" + maxid + "," + type + ",'" + text + "')");
    }

    public void Acctitem_edititem(String text, int id) {
        db.execSQL("update acctitem set name='" + text + "' where _id=" + id);
    }

    public void Acctitem_delitem(int id) {
        db.execSQL("delete from acctitem where _id=" + id);
    }

    public Cursor getParentNode() {
        return db.query("acctitem", new String[] { "_id", "name" },
                "pid is null", null, null, null, "pid,_id");
    }

    public Cursor getChildenNode(String pid) {
        return db.query("acctitem", new String[] { "_id", "name" },
                "pid=" + pid, null, null, null, "_id");
    }

    public void close() {
        db.close();
    }
}

小結與一點提醒

從 ExpandableListActivity 到自訂 Dialog,再到刷新機制,這一頁看下來似乎只是「錄入一筆帳」,實際卻橫跨了 UI 佈局、Cursor 綁定、Activity 之間的資料回傳與 SQLite 語法好幾個層面。

順帶一提,範例中的 SQL 是用字串拼接出來的。自己在練習時這樣寫沒問題,但若要發布給真實使用者,記得改用參數化查詢(selectionArgs 或 ContentValues),一方面是避免帳目名稱裡出現單引號時把語法弄壞,另一方面也能降低 SQL injection 的風險。這算是當年寫完之後回頭看,最想補上的一課。

下一篇再來談新增帳單頁面的下半部分:日期與時間的選擇、金額輸入,以及如何把 bills 這筆紀錄真正寫進資料庫。

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