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

Android 個人理財工具(三):添加賬單頁面(上)

編輯:關於 Android 程式設計

ColaBox 的收支登記終於進入比較複雜的部分了。這個介面我查了不少資料,也翻看了 Android 原始碼才完成——這時候會真切感受到 Google 開源的價值。

從登入頁面跳轉進入添加賬單頁面,它的主要任務就是登記收支記錄,說白了就是往資料庫寫入明細。

資料表結構

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

一、介面構想

一開始打算用 TableLayout 來排,最後定案的樣子如下:

首先要處理的是「賬目」欄位。賬目資料在之前的初始化階段已經寫入,它本身是個兩層結構(收入/支出作為父節點,具體項目作為子節點),因此適合用 ExpandableListActivity 呈現。

我在賬目欄位後面放了一個唯讀、沒有光標的 EditText,讓它看起來像輸入框但不能直接打字;點擊時打開賬目選擇介面。

圖 2 賬目選擇:

在這個介面中點擊子節點,就會把選中的賬目回傳給前一個頁面。但這裡有個問題:如果使用者要登錄的賬目還不存在怎麼辦?

正因如此,我沒有採用 Dialog 方案,而是用獨立的 ExpandableListActivity——這樣就能在長按子節點時彈出管理賬目的選單來維護資料。

圖 3 賬目選擇選單:

圖 4 編輯賬目:

流程說起來簡單,實際撰寫時遇到不少問題,不過逐一解決的過程也正是程式設計有趣的地方。

二、用 SimpleCursorTreeAdapter 建立兩層列表

關於 ExpandableListActivity,可以參考 Android SDK 中 ApiDemos 的 ExpandableList1、ExpandableList2、ExpandableList3 三個範例。其中 ExpandableList2 正是從資料庫讀取的例子。不過官方範例引用了 android.provider.Contacts.People(聯絡人框架),而我這裡是直接以 SQL 操作資料庫,做法不同。

其實只要準備好兩個游標——groupCursor 與 childCursor——其餘的都交給 SimpleCursorTreeAdapter:

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

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

// 建立 Adapter
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);


// 2. 子節點游標,等同 select * from acctitem where _id = 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);
    }

    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 做賬目名稱輸入

新增賬目時需要輸入名稱,所以需要一個類似 inputBox 的自訂 Dialog(即圖 4)。

AlertDialog 提供了很多現成選項——清單、樹狀清單、單選——但就是不能輸入文字。這裡我參考了 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);
        LinearLayout.LayoutParams param2 =
                new LinearLayout.LayoutParams(200, 50);
        layout.addView(edit, param2);

        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);   // 以回呼傳回輸入的資料
        }
    }
}

這樣自訂 Dialog 就完成了,新增與編輯賬目都能用它。

四、一個容易卡住的地方:如何刷新 Tree 列表

新增賬目之後,要怎麼讓列表反映變化?

一開始我以為只要呼叫 getExpandableListView().invalidate() 就行——在 ExpandableList1 那個範例裡,修改陣列後呼叫它確實能刷新畫面。但在這裡搭配 SimpleCursorTreeAdapter 卻行不通。

想通之後就明白了:既然資料來源是游標,那要刷新的應該是 Adapter。後來找到 notifyDataSetChanged(),果然可以。這個差異值得記住:資料來源是什麼,刷新方式就該對應什麼。

五、賬目管理頁面完整程式碼

package com.cola.ui;

import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;

/** 以 Cursor 為資料來源的展開式列表 */
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());
    }

    /** 點擊子節點:把選中的賬目回傳給上一頁 */
    @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;
    }

    /** 長按子節點時顯示管理選單 */
    @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().toString()
                            + "'這個賬目嗎?")
                    .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();
        }
    };

    /** 刷新列表: notifyDataSetChanged 才是正確做法 */
    private void updatedisplay() {
        ((MyExpandableListAdapter) mAdapter).notifyDataSetChanged();
    }

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

        @Override
        public long getGroupId(int groupPosition) {
            Cursor groupCursor = (Cursor) getGroup(groupPosition);
            return groupCursor.getLong(mGroupIdColumnIndex);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            Cursor childCursor = (Cursor) getChild(groupPosition, childPosition);
            return childCursor.getLong(0);
        }
    }
}

六、資料庫管理程式碼

package com.cola.ui;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/** 提供賬目與賬單資料表的存取 */
public class BilldbHelper {

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

    BilldbHelper(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.");
        }
    }

    public void CreateTable_bills() {
        try {
            db.execSQL("CREATE TABLE bills ("
                    + "_ID INTEGER PRIMARY KEY,"
                    + " acctitemid integer,"
                    + " fee integer,"
                    + " userid integer,"
                    + " sdate TEXT,"
                    + " stime TEXT,"
                    + " desc TEXT"
                    + ");");
        } catch (Exception e) {
            Log.v("cola", "Create Table bills err, table exists.");
        }
    }

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

    /** 初始化預設賬目 */
    public void InitAcctitem() {
        try {
            db.execSQL("insert into acctitem values (1,null,'收入')");
            db.execSQL("insert into acctitem values (2,1,'工資')");
            db.execSQL("insert into acctitem values (9998,1,'其他')");
            db.execSQL("insert into acctitem values (0,null,'支出')");
            db.execSQL("insert into acctitem values (3,0,'生活用品')");
            db.execSQL("insert into acctitem values (4,0,'水電煤氣費')");
            db.execSQL("insert into acctitem values (5,0,'汽油費')");
            db.execSQL("insert into acctitem values (9999,0,'其他')");
        } catch (Exception e) {
            Log.v("cola", "init acctitem e=" + e.getMessage());
        }
    }

    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 void FirstStart() {
        try {
            String col[] = {"type", "name"};
            Cursor c = db.query("sqlite_master", col, "name='colaconfig'",
                                null, null, null, null);
            if (c.getCount() == 0) {
                CreateTable_acctitem();
                CreateTable_colaconfig();
                CreateTable_bills();
                InitAcctitem();
            }
        } catch (Exception e) {
            Log.v("cola", "e=" + e.getMessage());
        }
    }

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

幾點回顧

這個介面把不少元件湊在一起:展開式列表、自訂 Dialog、Activity 之間的結果回傳,以及資料庫的增刪改。寫完之後有兩個體會值得記下。

第一,官方 ApiDemos 的價值遠勝於多數教學文章。當你遇到的是標準元件的使用問題,直接讀原始碼往往比搜尋解答更快。

第二,資料庫操作最好避開字串拼接。範例中 Acctitem_newitem() 等方法直接組 SQL 字串,在賬目名稱由使用者輸入的情況下,一旦名稱含單引號就會出錯,也有注入風險。實務上應改用 SQLiteStatement 或 db.insert() 的參數化寫法。

系列文章:

  • Android 個人理財工具六:顯示賬單明細(下)
  • Android 個人理財工具五:顯示賬單明細(上)
  • Android 個人理財工具四:添加賬單頁面(下)
  • Android 個人理財工具三:添加賬單頁面(上)
  • Android 個人理財工具二:使用 SQLite 實現啟動時初始化資料
  • Android 個人理財工具一:專案概述與啟動介面的實現
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved