Android 个人理财工具三:添加账单页面 上

Android 个人理财工具三:添加账单页面 上,第1张

概述      ColaBox登记收支记录终于进入了复杂阶段了。这个界面我也是查找了很多资料以及打开android的源代码看了后才完成了,现在想来Google的开源真是明智的啊。

       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 账目选择:

@H_404_33@

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

       所以我这没有用dialog方式而是用了ExpandableListActivity。在这个界面中如果长点某个子节点就d出管理账目菜单,来维护账目,如下图所示:

       图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。

Java代码      

//首先要实现groupcursor就是父节点游标,这个其实就是我的acctitem表的 //select * from accitem where pID is null 的结果 Cursor groupCursor = billdb.getparentNode();   // Cache the ID column index mGroupIDColumnIndex = groupCursor.getColumnIndexOrThrow("_ID");   // Set up our adapter mAdapter = new Myexpandablelistadapter(groupCursor,this,androID.R.layout.simple_expandable_List_item_1,new String[] { "name" },// name for group layouts   new int[] { androID.R.ID.text1 },//   new int[] { androID.R.ID.text1 }); setlistadapter(mAdapter); //然后我要实现childCursor //其实就是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) + "";  // Log.v("cola","pID="+pID);  return billdb.getChildenNode(pID);  } } //我们看看Billdbhelper里面的cursor  public Cursor getparentNode(){   return db.query("acctitem",new String[]{"_ID","name" },"pID is null",null,"pID,_ID");     }    public Cursor getChildenNode(String pID){   Log.v("cola","run getchildenNode");   return db.query("acctitem","pID="+pID,"_ID");   } //只要这几步一个2级的tree List就可以出现了. 

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

       虽然alertDialog提供了很多方法,可以选择List、treeList、radio,可惜就是不能录入text。

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

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

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

Java代码

// 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;   TextVIEw label = new TextVIEw(context);   label.setText("hint");   // setVIEw(label);   edit = new EditText(context);   edit.setText(value);   layout = new linearLayout(context);   layout.setorIEntation(linearLayout.VERTICAL);   // linearLayout.LayoutParams param =   // new linearLayout.LayoutParams(100,40);   // layout.addVIEw(label,param);   linearLayout.LayoutParams param2 = new linearLayout.LayoutParams(200,50);   layout.addVIEw(edit,param2);   //添加edit   setVIEw(layout);   setTitle(Title);   setbutton("确定",this);   setbutton2("取消",(OnClickListener) null);  }  public voID onClick(DialogInterface dialog,int which) {   // Log.v("cola","U click which="+which);   text = edit.getText().toString();   Log.v("cola","U click text=" + text);   if (mCallback != null)    mCallback.onDateSet(text); //使用回调返回录入的数据  } } 

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

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

       在这我开始以为只要使用getExpandableListVIEw().invalIDate(); 就可以了。

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

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

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

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

       首先是账目管理:

Java代码

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.provIDer.Contacts.People; 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; /**  * Demonstrates expandable Lists backed by Cursors  */ public class Frm_Editacctitem extends ExpandableListActivity {  private int mGroupIDColumnIndex;  private String mPhoneNumberProjection[] = new String[] { People.Phones._ID,People.Phones.NUMBER };  private expandablelistadapter mAdapter;  BilldbHelper billdb;  Dialog_edit newdialog;      private ExpandableListContextMenuInfo info;      @OverrIDe  public voID onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setTitle("ColaBox-选择账目");   billdb = new BilldbHelper(this);   // query for people   Cursor groupCursor = billdb.getparentNode();   // Cache the ID column index   mGroupIDColumnIndex = groupCursor.getColumnIndexOrThrow("_ID");   // Set up our adapter   mAdapter = new Myexpandablelistadapter(groupCursor,// name for group layouts     new int[] { androID.R.ID.text1 },//     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());//给bundle 写入数据   Intent mIntent = new Intent();   mIntent.putExtras(bundle);   setResult(RESulT_OK,mIntent);   billdb.close();   finish();   return true;   }  @OverrIDe  public voID onCreateContextMenu(ContextMenu menu,ContextMenuInfo menuInfo) {   super.onCreateOptionsMenu(menu);   if (ExpandableListVIEw     .getPackedpositionType(((ExpandableListContextMenuInfo) menuInfo).packedposition) == 1) {    Log.v("cola","run menu");    menu.setheaderTitle("菜单");    menu.add(0,1,"新 增");    menu.add(0,2,"删 除");    menu.add(0,3,"编 辑");   }  }  @OverrIDe  public boolean onContextItemSelected(MenuItem item) {   info = (ExpandableListContextMenuInfo) item.getMenuInfo();   if (item.getItemID() == 1) {    // Log.v("cola","ID"+info.ID);    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("取消",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) {    Log.v("cola","new acctitem");    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();   }  };  private voID updatedisplay(){   Log.v("cola","update display");   ((Myexpandablelistadapter)mAdapter).notifyDataSetChanged();  }    public class Myexpandablelistadapter extends SimpleCursorTreeAdapter {   public Myexpandablelistadapter(Cursor cursor,int[] childrenTo) {    super(context,childrenTo);   }   @OverrIDe   protected Cursor getChildrenCursor(Cursor groupCursor) {    String pID = groupCursor.getLong(mGroupIDColumnIndex) + "";    // Log.v("cola","pID="+pID);    return billdb.getChildenNode(pID);   }   @OverrIDe   public long getGroupID(int groupposition) {    // Log.v("cola","getGroupID " + groupposition);    Cursor groupCursor = (Cursor) getGroup(groupposition);    return groupCursor.getLong(mGroupIDColumnIndex);   }   @OverrIDe   public long getChildID(int groupposition,int childposition) {    // Log.v("cola","getChildID " + groupposition + "," +    // childposition);    Cursor childCursor = (Cursor) getChild(groupposition,childposition);    return childCursor.getLong(0);   }  } } 

       自定义对话框:

Java代码

package com.cola.ui; import androID.app.AlertDialog; import androID.content.Context; import androID.content.DialogInterface; import androID.content.DialogInterface.OnClickListener; import androID.util.Log; import androID.Widget.EditText; import androID.Widget.linearLayout; import androID.Widget.TextVIEw; 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,param2);   setVIEw(layout);   setTitle(Title);   setbutton("确定","U click text=" + text);   if (mCallback != null)    mCallback.onDateSet(text);  } } 

       数据库管理代码:

Java代码

package com.cola.ui; import androID.content.Context; import androID.database.Cursor; import androID.database.sqlite.sqliteDatabase; import androID.util.Log; /**  * ProvIDes access to a database of notes. Each note has a Title,the note  * itself,a creation date and a modifIEd data.  */ 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,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"          + ");");    Log.v("cola","Create table acctitem ok");   }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"          + ");");        Log.v("cola",table exists.");   }  }    public voID Createtable_colaconfig() {   try{    db.execsql("CREATE table colaconfig ("      + "_ID INTEGER PRIMARY KEY,"      + "name TEXT"         + ");");    Log.v("cola","Create table colaconfig ok");   }catch(Exception e){    Log.v("cola",table exists.");   }  }    public voID Initacctitem() {   try{    //s.getBytes(enCoding);    db.execsql("insert into acctitem values (1,'收入')");    db.execsql("insert into acctitem values (2,'工资')");    db.execsql("insert into acctitem values (9998,'其他')");    db.execsql("insert into acctitem values (0,'支出')");    db.execsql("insert into acctitem values (3,'生活用品')");    db.execsql("insert into acctitem values (4,'水电煤气费')");    db.execsql("insert into acctitem values (5,'汽油费')");    db.execsql("insert into acctitem values (9999,'其他')");        //db.execsql("insert into bills values(100,135,10000,'','备注')");    Log.v("cola","insert into ok");   }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);   c.movetoFirst();   int maxID=c.getInt(0);     String sql="insert into acctitem values ("+maxID+","+type+",'"+text+"')";   db.execsql(sql);   Log.v("cola","newitem ok text="+text+" ID="+type+" sql="+sql);     }    public voID Acctitem_edititem(String text,int ID){     db.execsql("update acctitem set name='"+text+"' where _ID="+ID);   Log.v("cola","edititem ok text="+text+" ID="+ID);  }    public voID Acctitem_delitem(int ID){      db.execsql("delete from acctitem where _ID="+ID);   Log.v("cola","delitem ok ID="+ID);  }    public voID querytable_acctitem(){     }    public voID FirstStart(){   try{    String col[] = {"type","name" };    Cursor c =db.query("sqlite_master",col,"name='colaconfig'",null);    int n=c.getCount();    if (c.getCount()==0){     Createtable_acctitem();     Createtable_colaconfig();     Createtable_bills();     Initacctitem();      }       //getTree();       Log.v("cola","c.getCount="+n+"");             }catch(Exception e){    Log.v("cola","e="+e.getMessage());   }        }      public voID close(){   db.close();  }    public Cursor getparentNode(){   return db.query("acctitem",_ID");      }    public Cursor getChildenNode(String pID){   Log.v("cola","_ID");   }   } 

        系列文章:

                       Android 个人理财工具六:显示账单明细 下

                       Android 个人理财工具五:显示账单明细 上

                       Android 个人理财工具四:添加账单页面 下

                       Android 个人理财工具三:添加账单页面 上

                       Android 个人理财工具二:使用SQLite实现启动时初始化数据

                       Android 个人理财工具一:项目概述与启动界面的实现

       以上就AndroID 开发个人理财工具 添加账单页面的讲解,后续继续更新相应文章,谢谢大家对本站的支持!

总结

以上是内存溢出为你收集整理的Android 个人理财工具三:添加账单页面 上全部内容,希望文章能够帮你解决Android 个人理财工具三:添加账单页面 上所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1148416.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存