(Android studio家庭記賬本源碼已上傳至github,https://github.com/xhj1074376195/CostBook_app)
今天記賬本終於可以算是完成了,實現了賬戶余額的計算。就是下面兩段關鍵代碼來實現
//計算數據庫表"TABLE"中"cost_money"這一列中的總和,即賬戶余額
public int countTotalCost(){ int sum=0; SQLiteDatabase database=getWritableDatabase(); String sum_dbString="select sum(cost_money)from "+TABLE; Cursor cursor=database.rawQuery(sum_dbString,null); if (cursor!=null){ if (cursor.moveToFirst()){ do{ sum=cursor.getInt(0); }while (cursor.moveToNext()); } } return sum; }
在activity.xml中添加一個TextView
<TextView android:id="@+id/tv_cost_total" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="60dp" android:textSize="15dp" android:text="賬戶余額:0"/>
將求得的余額直接轉換為字符串賦值給TextView
String string_total_cost="賬戶余額:"+mDatabaseHelper.countTotalCost(); costTotal =findViewById(R.id.tv_cost_total); costTotal.setText(string_total_cost);
家庭記賬本到這里就可以算是完成了,總的來說,實現了增加收入,增加支出,根據名稱刪除賬單和清空賬單,自動計算賬戶余額5個功能。
但是最后呢,還是有一點小小的瑕疵.......那就是如果賬單過多,超過了一頁,最下面的四個按鈕會把最后一條記錄給擋住,,,,,。