Android 实例-个人理财工具 之三 添加账单页面A

键字:android sdk1.0 sqlite intent ExpandableListActivity SimpleCursorTreeAdapter cursor custom dialog

 

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来布局

最后布局就是如下图这样

 

图1

 

在这儿我首先需要设置账目,前面我们已经初始化过账目的数据.

账目应该是一个ExpandableListActivity 2层的结构.需要从数据库里面读取.我在账目后面放了一个editview 只读没有光标的.也就是在这儿不可录入,在该editview的onclick事件里面我们打开账目选择界面.如下图

 

图2 账目选择

 

在这个界面中点击子节点就返回前面界面,把选择的账目传递过去.在这有个问题,如果用户需要录入的账目没有怎么办?

所以我这没有用dialog方式而是用了ExpandableListActivity  在这个界面中如果长点某个子节点就弹出管理账目菜单,

来维护账目,如下图所示:

图3账目选择菜单示意                                                                    图4 编辑账目

 

 上面这些流程说起来很简单,可是当我用andriod编写时,遇到了很多问题,不过一个个都被我解决了,这正是编程的快乐所在.

关于ExpandableListActivity 大家可以参考android 里面apidemos 里面ExpandableList1,ExpandableList2,ExpandableList3

这里面对熟悉这个ui还是很有帮助的. 在ExpandableList2 里面就是从数据库进行读取的例子. 当然android里面那个我是没太

看明白因为他引用了import android.provider.Contacts.People; 联系人部分的框架,而我目前对数据库的操作和他不一样,我都是直接

sql访问.

但是你只要搞定2个cursor就ok了. Cursor groupCursor childCursor 其他都由SimpleCursorTreeAdapter帮你实现了.

下面我们来看看如何使用SimpleCursorTreeAdapter

  1. //首先要实现groupcursor就是父节点游标,这个其实就是我的acctitem表的
  2. //select * from accitem where pid is null 的结果
  3. Cursor groupCursor = billdb.getParentNode();
  4.          // Cache the ID column index
  5. mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow( "_ID" );
  6.          // Set up our adapter
  7. mAdapter =  new  MyExpandableListAdapter(groupCursor,  this ,       android.R.layout.simple_expandable_list_item_1,
  8.     android.R.layout.simple_expandable_list_item_1,
  9.          new  String[] {  "NAME"  },  // Name for group layouts
  10.          new   int [] { android.R.id.text1 }, 
  11.          new  String[] {  "NAME"  },  //
  12.          new   int [] { android.R.id.text1 });
  13. setListAdapter(mAdapter);
  14. //然后我要实现childCursor 
  15. //其实就是select * from acctitem where id=pid 的结果
  16. public   class  MyExpandableListAdapter extends SimpleCursorTreeAdapter {
  17. public  MyExpandableListAdapter(Cursor cursor, Context context,
  18.                  int  groupLayout,  int  childLayout, String[] groupFrom,
  19.                  int [] groupTo, String[] childrenFrom,  int [] childrenTo)
  20.  {
  21.             super(context, cursor, groupLayout, groupFrom, groupTo,
  22.                     childLayout, childrenFrom, childrenTo);
  23.   }
  24. protected Cursor getChildrenCursor(Cursor groupCursor) {
  25.    String pid = groupCursor.getLong(mGroupIdColumnIndex) + "";
       // Log.v("cola","pid="+pid);
       return billdb.getChildenNode(pid);
  26.   }
  27. }
  28. //我们看看Billdbhelper里面的cursor
  29.    public Cursor getParentNode(){
         return db.query("acctitem", new String[]{"_id", "name" }, "pid is null", null, null, null, "pid,_id");     
     
        }
       
        public Cursor getChildenNode(String pid){
         Log.v("cola","run getchildenNode");
         return db.query("acctitem", new String[]{"_id", "name" }, "pid="+pid, null, null, null, "_id");     
  30.     }
  31. 只要这几步一个2级的tree list就可以出现了.

上面其实才是刚开始,后面我们需要使用一个自定义的Dialog 类似于一个inputBox 因为我们新增账目是需要输入账目的名称.

就是上面图4表现的.

虽然alertDialog提供了很多方法,可以选择list,treelist,radio, 可惜就是不能录入text.

这里我参考了api demos 里面的 DateWidgets1.java 和源代码里面DatePickerDialog.java .

我们可以从alertdialog 继承.然后添加一个Editview 最后把数据返回出来.只要把上面我说的2个java看清楚了后处理起来就简单了.

主要是一个回调函数的用法.下面看代码

  1. //
  2. public   class  Dialog_edit extends AlertDialog implements OnClickListener {
  3.      private  String text =  "" ;
  4.      private  EditText edit;
  5.      private  OnDateSetListener mCallback; //定义回调函数
  6.      private  LinearLayout layout;
  7.      public   interface  OnDateSetListener {  //回调接口
  8.          void  onDateSet(String text);
  9.     }
  10.      protected  Dialog_edit(Context context, String title, String value,
  11.             OnDateSetListener Callback) {
  12.         super(context);
  13.         mCallback = Callback;
  14.         TextView label =  new  TextView(context);
  15.         label.setText( "hint" );
  16.          // setView(label);
  17.         edit =  new  EditText(context);
  18.         edit.setText(value);
  19.         layout =  new  LinearLayout(context);
  20.         layout.setOrientation(LinearLayout.VERTICAL);
  21.          // LinearLayout.LayoutParams param =
  22.          // new LinearLayout.LayoutParams(100, 40);
  23.          // layout.addView(label, param);
  24.         LinearLayout.LayoutParams param2 =  new  LinearLayout.LayoutParams(200,
  25.                 50);
  26.         layout.addView(edit, param2);
  27.        //添加edit
  28.         setView(layout);
  29.         setTitle(title);
  30.         setButton( "确定"this );
  31.         setButton2( "取消" , (OnClickListener)  null );
  32.     }
  33.      public   void  onClick(DialogInterface dialog,  int  which) {
  34.          // Log.v("cola","U click which="+which);
  35.         text = edit.getText().toString();
  36.         Log.v( "cola""U click text="  + text);
  37.          if  (mCallback !=  null )
  38.             mCallback.onDateSet(text);  //使用回调返回录入的数据
  39.     }
  40. }

这样我们就完成了自定义的dialog 我们可以使用它来新增和编辑账目. 对于账目的增删改就是sql的事情了

在这我又遇到一个问题就是我新增一个账目后如何来刷新界面,从而反映账目修改后的变化

在这我开始以为只要使用 getExpandableListView().invalidate(); 就可以了,

因为我之前在ExpandableList1.java例子里面,使用它可以刷新界面.

在那个例子里面我修改了数组后调用该方法,界面就刷新了,而在这SimpleCursorTreeAdapter就行不通了,我想

应该只要刷新cursor应该就可以了,后来找到了notifyDataSetChanged 呵呵,果然可以了. 这样账目的录入和管理就搞定了.

 

下面给出目前最新的代码.

首先是账目管理

  1. package com.cola.ui;
  2. import android.app.AlertDialog;
  3. import android.app.ExpandableListActivity;
  4. import android.content.Context;
  5. import android.content.DialogInterface;
  6. import android.content.Intent;
  7. import android.database.Cursor;
  8. import android.os.Bundle;
  9. import android.provider.Contacts.People;
  10. import android.util.Log;
  11. import android.view.ContextMenu;
  12. import android.view.MenuItem;
  13. import android.view.View;
  14. import android.view.ContextMenu.ContextMenuInfo;
  15. import android.widget.ExpandableListAdapter;
  16. import android.widget.ExpandableListView;
  17. import android.widget.SimpleCursorTreeAdapter;
  18. import android.widget.TextView;
  19. import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
  20. /**
  21.  * Demonstrates expandable lists backed by Cursors
  22.  */
  23. public   class  Frm_Editacctitem extends ExpandableListActivity {
  24.      private   int  mGroupIdColumnIndex;
  25.      private  String mPhoneNumberProjection[] =  new  String[] { People.Phones._ID,
  26.             People.Phones.NUMBER };
  27.      private  ExpandableListAdapter mAdapter;
  28.     BilldbHelper billdb;
  29.     Dialog_edit newdialog;
  30.     
  31.     
  32.      private  ExpandableListContextMenuInfo info;
  33.     
  34.     
  35.     @Override
  36.      public   void  onCreate(Bundle savedInstanceState) {
  37.         super.onCreate(savedInstanceState);
  38.         setTitle( "ColaBox-选择账目" );
  39.         billdb =  new  BilldbHelper( this );
  40.          // Query for people
  41.         Cursor groupCursor = billdb.getParentNode();
  42.          // Cache the ID column index
  43.         mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow( "_ID" );
  44.          // Set up our adapter
  45.         mAdapter =  new  MyExpandableListAdapter(groupCursor,  this ,
  46.                 android.R.layout.simple_expandable_list_item_1,
  47.                 android.R.layout.simple_expandable_list_item_1,
  48.                  new  String[] {  "NAME"  },  // Name for group layouts
  49.                  new   int [] { android.R.id.text1 },  new  String[] {  "NAME"  },  //
  50.                  new   int [] { android.R.id.text1 });
  51.         setListAdapter(mAdapter);
  52.         registerForContextMenu(getExpandableListView());
  53.     }
  54.     
  55.     @Override
  56.      public  boolean onChildClick(ExpandableListView parent, View v,  int  groupPosition,  int  childPosition,  long  id)
  57.     {
  58.         Bundle bundle =  new  Bundle();
  59.         bundle.putString( "DataKey" , ((TextView)v).getText().toString()); //给bundle 写入数据
  60.         Intent mIntent =  new  Intent();
  61.         mIntent.putExtras(bundle);
  62.         setResult(RESULT_OK, mIntent);
  63.         billdb.close();
  64.         finish(); 
  65.          return   true ;    
  66.     }
  67.     @Override
  68.      public   void  onCreateContextMenu(ContextMenu menu, View v,
  69.             ContextMenuInfo menuInfo) {
  70.         super.onCreateOptionsMenu(menu);
  71.          if  (ExpandableListView
  72.                 .getPackedPositionType(((ExpandableListContextMenuInfo) menuInfo).packedPosition) == 1) {
  73.             Log.v( "cola""run menu" );
  74.             menu.setHeaderTitle( "菜单" );
  75.             menu.add(0, 1, 0,  "新 增" );
  76.             menu.add(0, 2, 0,  "删 除" );
  77.             menu.add(0, 3, 0,  "编 辑" );
  78.         }
  79.     }
  80.     @Override
  81.      public  boolean onContextItemSelected(MenuItem item) {
  82.         info = (ExpandableListContextMenuInfo) item.getMenuInfo();
  83.          if  (item.getItemId() == 1) {
  84.              // Log.v("cola","id"+info.id);
  85.             newdialog =  new  Dialog_edit( this"请输入新增账目的名称""" ,
  86.                     mDialogClick_new);
  87.             newdialog.show();
  88.         }  else   if  (item.getItemId() == 2) {
  89.              new  AlertDialog.Builder( this ).setTitle( "提示" ).setMessage( "确定要删除'" +((TextView)info.targetView).getText().toString()+ "'这个账目吗?" )
  90.                     .setIcon(R.drawable.quit).setPositiveButton( "确定" ,
  91.                              new  DialogInterface.OnClickListener() {
  92.                                  public   void  onClick(DialogInterface dialog,
  93.                                          int  whichButton) {
  94.                                     billdb.Acctitem_delitem(( int )info.id);
  95.                                     updatedisplay();
  96.                                 }
  97.                             }).setNegativeButton( "取消" ,
  98.                              new  DialogInterface.OnClickListener() {
  99.                                  public   void  onClick(DialogInterface dialog,
  100.                                          int  whichButton) {
  101.                                      // 取消按钮事件
  102.                                 }
  103.                             }).show();
  104.         }  else   if  (item.getItemId() == 3) {
  105.             newdialog =  new  Dialog_edit( this"请修改账目名称" ,
  106.                     ((TextView) info.targetView).getText().toString(),
  107.                     mDialogClick_edit);
  108.             newdialog.show();
  109.         }
  110.          return   false ;
  111.     }
  112.      private  Dialog_edit.OnDateSetListener mDialogClick_new =  new  Dialog_edit.OnDateSetListener() {
  113.          public   void  onDateSet(String text) {
  114.             Log.v( "cola""new acctitem" );
  115.             billdb.Acctitem_newitem(text,ExpandableListView.getPackedPositionGroup(info.packedPosition));
  116.             updatedisplay();
  117.         }
  118.     };
  119.     
  120.      private  Dialog_edit.OnDateSetListener mDialogClick_edit =  new  Dialog_edit.OnDateSetListener() {
  121.          public   void  onDateSet(String text) {            
  122.             billdb.Acctitem_edititem(text,( int )info.id);
  123.             updatedisplay();
  124.         }
  125.     };
  126.      private   void  updatedisplay(){
  127.         Log.v( "cola""update display" );
  128.         ((MyExpandableListAdapter)mAdapter).notifyDataSetChanged();
  129.     }
  130.     
  131.      public   class  MyExpandableListAdapter extends SimpleCursorTreeAdapter {
  132.          public  MyExpandableListAdapter(Cursor cursor, Context context,
  133.                  int  groupLayout,  int  childLayout, String[] groupFrom,
  134.                  int [] groupTo, String[] childrenFrom,  int [] childrenTo) {
  135.             super(context, cursor, groupLayout, groupFrom, groupTo,
  136.                     childLayout, childrenFrom, childrenTo);
  137.         }
  138.         @Override
  139.          protected  Cursor getChildrenCursor(Cursor groupCursor) {
  140.             String pid = groupCursor.getLong(mGroupIdColumnIndex) +  "" ;
  141.              // Log.v("cola","pid="+pid);
  142.              return  billdb.getChildenNode(pid);
  143.         }
  144.         @Override
  145.          public   long  getGroupId( int  groupPosition) {
  146.              // Log.v("cola", "getGroupId " + groupPosition);
  147.             Cursor groupCursor = (Cursor) getGroup(groupPosition);
  148.              return  groupCursor.getLong(mGroupIdColumnIndex);
  149.         }
  150.         @Override
  151.          public   long  getChildId( int  groupPosition,  int  childPosition) {
  152.              // Log.v("cola", "getChildId " + groupPosition + "," +
  153.              // childPosition);
  154.             Cursor childCursor = (Cursor) getChild(groupPosition, childPosition);
  155.              return  childCursor.getLong(0);
  156.         }
  157.     }
  158. }

自定义对话框

  1. package com.cola.ui;
  2. import android.app.AlertDialog;
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.content.DialogInterface.OnClickListener;
  6. import android.util.Log;
  7. import android.widget.EditText;
  8. import android.widget.LinearLayout;
  9. import android.widget.TextView;
  10. public   class  Dialog_edit extends AlertDialog implements OnClickListener {
  11.      private  String text =  "" ;
  12.      private  EditText edit;
  13.      private  OnDateSetListener mCallback;
  14.      private  LinearLayout layout;
  15.      public   interface  OnDateSetListener {
  16.          void  onDateSet(String text);
  17.     }
  18.      protected  Dialog_edit(Context context, String title, String value,
  19.             OnDateSetListener Callback) {
  20.         super(context);
  21.         mCallback = Callback;
  22.         TextView label =  new  TextView(context);
  23.         label.setText( "hint" );
  24.          // setView(label);
  25.         edit =  new  EditText(context);
  26.         edit.setText(value);
  27.         layout =  new  LinearLayout(context);
  28.         layout.setOrientation(LinearLayout.VERTICAL);
  29.          // LinearLayout.LayoutParams param =
  30.          // new LinearLayout.LayoutParams(100, 40);
  31.          // layout.addView(label, param);
  32.         LinearLayout.LayoutParams param2 =  new  LinearLayout.LayoutParams(200,
  33.                 50);
  34.         layout.addView(edit, param2);
  35.         setView(layout);
  36.         setTitle(title);
  37.         setButton( "确定"this );
  38.         setButton2( "取消" , (OnClickListener)  null );
  39.     }
  40.      public   void  onClick(DialogInterface dialog,  int  which) {
  41.          // Log.v("cola","U click which="+which);
  42.         text = edit.getText().toString();
  43.         Log.v( "cola""U click text="  + text);
  44.          if  (mCallback !=  null )
  45.             mCallback.onDateSet(text);
  46.     }
  47. }

数据库管理代码

  1. package com.cola.ui;
  2. import android.content.Context;
  3. import android.database.Cursor;
  4. import android.database.sqlite.SQLiteDatabase;
  5. import android.util.Log;
  6. /**
  7.  * Provides access to a database of notes. Each note has a title, the note
  8.  * itself, a creation date and a modified data.
  9.  */
  10. public   class  BilldbHelper {
  11.      private   static  final String TAG =  "Cola_BilldbHelper" ;
  12.      private   static  final String DATABASE_NAME =  "cola.db" ;
  13.     
  14.     SQLiteDatabase db;
  15.     Context context;
  16.     
  17.     BilldbHelper(Context _context) {
  18.         context=_context;
  19.         db=context.openOrCreateDatabase(DATABASE_NAME, 0,  null ); 
  20.         Log.v(TAG, "db path=" +db.getPath());
  21.     }
  22.     
  23.      public   void  CreateTable_acctitem() {
  24.          try {
  25.             db.execSQL( "CREATE TABLE acctitem ("
  26.                     +  "_ID INTEGER PRIMARY KEY,"
  27.                     +  "PID integer,"
  28.                     +  "NAME TEXT"                
  29.                     +  ");" );
  30.             Log.v( "cola" , "Create Table acctitem ok" );
  31.         } catch (Exception e){
  32.             Log.v( "cola" , "Create Table acctitem err,table exists." );
  33.         }
  34.     }
  35.     
  36.      public   void  CreateTable_bills() {
  37.          try {
  38.             db.execSQL( "CREATE TABLE bills ("
  39.                     +  "_ID INTEGER PRIMARY KEY,"
  40.                     + " acctitemid integer,"    
  41.                     +  "fee integer,"
  42.                     +  "userid integer,"
  43.                     +  "sdate TEXT,"
  44.                     +  "stime TEXT,"
  45.                     +  "desc TEXT"                 
  46.                     +  ");" );
  47.             
  48.             Log.v( "cola" , "Create Table acctitem ok" );
  49.         } catch (Exception e){
  50.             Log.v( "cola" , "Create Table acctitem err,table exists." );
  51.         }
  52.     }
  53.     
  54.      public   void  CreateTable_colaconfig() {
  55.          try {
  56.             db.execSQL( "CREATE TABLE colaconfig ("
  57.                     +  "_ID INTEGER PRIMARY KEY,"
  58.                     +  "NAME TEXT"             
  59.                     +  ");" );
  60.             Log.v( "cola" , "Create Table colaconfig ok" );
  61.         } catch (Exception e){
  62.             Log.v( "cola" , "Create Table acctitem err,table exists." );
  63.         }
  64.     }
  65.     
  66.      public   void  InitAcctitem() {
  67.          try {
  68.            //s.getBytes(encoding);
  69.           db.execSQL( "insert into acctitem values (1,null,'收入')" );
  70.           db.execSQL( "insert into acctitem values (2,1,'工资')" );
  71.           db.execSQL( "insert into acctitem values (9998,1,'其他')" );
  72.           db.execSQL( "insert into acctitem values (0,null,'支出')" );
  73.           db.execSQL( "insert into acctitem values (3,0,'生活用品')" );
  74.           db.execSQL( "insert into acctitem values (4,0,'水电煤气费')" );
  75.           db.execSQL( "insert into acctitem values (5,0,'汽油费')" );
  76.           db.execSQL( "insert into acctitem values (9999,0,'其他')" );
  77.           
  78.            //db.execSQL("insert into bills values(100,135,10000,'','','备注')");
  79.           Log.v( "cola" , "insert into ok" ); 
  80.         } catch (Exception e)
  81.         {
  82.             Log.v( "cola" , "init acctitem e=" +e.getMessage());
  83.         }
  84.         
  85.     }
  86.      public   void  Acctitem_newitem(String text, int  type){
  87.         
  88.         Cursor c =db.query( "acctitem"new  String[]{ "max(_id)+1" },  "_id is not null and _id<9998"nullnullnullnull );
  89.         c.moveToFirst();
  90.          int  maxid=c.getInt(0);      
  91.         String sql= "insert into acctitem values (" +maxid+ "," +type+ ",'" +text+ "')" ;
  92.         db.execSQL(sql);
  93.         Log.v( "cola" , "newitem ok text=" +text+ " id=" +type+ " sql=" +sql);
  94.         
  95.     }
  96.     
  97.      public   void  Acctitem_edititem(String text, int  id){      
  98.         db.execSQL( "update acctitem set name='" +text+ "' where _id=" +id);
  99.         Log.v( "cola" , "edititem ok text=" +text+ " id=" +id);
  100.     }
  101.     
  102.      public   void  Acctitem_delitem( int  id){
  103.         
  104.         db.execSQL( "delete from acctitem where _id=" +id);
  105.         Log.v( "cola" , "delitem ok id=" +id);
  106.     }
  107.     
  108.      public   void  QueryTable_acctitem(){
  109.         
  110.     }
  111.     
  112.      public   void  FirstStart(){
  113.          try {
  114.             String col[] = { "type""name"  };
  115.             Cursor c =db.query( "sqlite_master" , col,  "name='colaconfig'"nullnullnullnull );
  116.              int  n=c.getCount();
  117.              if  (c.getCount()==0){
  118.                 CreateTable_acctitem();
  119.                 CreateTable_colaconfig();
  120.                 CreateTable_bills();
  121.                 InitAcctitem();         
  122.             }           
  123.              //getTree();            
  124.             Log.v( "cola" , "c.getCount=" +n+ "" );
  125.                     
  126.             
  127.         } catch (Exception e){
  128.             Log.v( "cola" , "e=" +e.getMessage());
  129.         }
  130.         
  131.         
  132.     }
  133.     
  134.     
  135.      public   void  close(){
  136.         db.close();
  137.     }
  138.     
  139.      public  Cursor getParentNode(){
  140.          return  db.query( "acctitem"new  String[]{ "_id""name"  },  "pid is null"nullnullnull"pid,_id" );      
  141.   
  142.     }
  143.     
  144.      public  Cursor getChildenNode(String pid){
  145.         Log.v( "cola" , "run getchildenNode" );
  146.          return  db.query( "acctitem"new  String[]{ "_id""name"  },  "pid=" +pid,  nullnullnull"_id" );     
  147.     }
  148.    
  149. }

 

这段代码搞了2个通宵.昨天晚上又被ubuntu 8.04和vmware 5.5 折腾死.我的周末就这样泡汤了.

##############################################

2008-11-23 01:43 湖北武汉

 

 

 

##############################################

备注:

      今天看了下android的dialog例子,发现android 带了可输入文字的dialog例子,呵呵,实际上和我自定义的方法就是类似的.

我之前还是demo看的太少了,也就不会走弯路了.

      具体可以看AlertDialogSamples.java

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值