Android开发之SQLite(手机记账App)

3

 

MainActivity.class 源码片段

private static final String TAG = "SQLiteLOG";
private MenuSelect menuSelect;
public int _id;
private Button but_save,but_update,but_delete;
private EditText name,money,remark;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setVisibility(0);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    name = (EditText)findViewById(R.id.item_name);
    money = (EditText)findViewById(R.id.item_money);
    remark = (EditText)findViewById(R.id.item_remark);

    Bundle bundle = getIntent().getExtras();
    if(bundle != null){
        _id = Integer.valueOf(bundle.getString("id"));
        name.setText(bundle.getString("name"));
        money.setText(bundle.getString("money"));
        remark.setText(bundle.getString("remark"));

    }
    init(this);


}

private void init(Context mContext) {

    but_save = (Button)findViewById(R.id.but_add);
    but_update = (Button)findViewById(R.id.but_edit);
    but_delete = (Button)findViewById(R.id.but_del);


    but_save.setOnClickListener(new ButClickListenter(mContext, name, money, remark,1,_id));
    but_update.setOnClickListener(new ButClickListenter(mContext, name, money, remark,2,_id));
    but_delete.setOnClickListener(new ButClickListenter(mContext, name, money, remark, 3, _id));

}

 

ButClickListenter.class按钮事件监听类源码
package com.test.sqlitetest;
import android.content.ContentValues;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Date;

/**
 * Created by Alan on 2016/05/13 0013.
 */
public class ButClickListenter implements View.OnClickListener {
 int type = 0;
 private static final String TAG = "ButClickListenterLOG";
 private EditText name,money,remark;
 private Context mContext;
 private DBbridge dBbridge;
 private ContentValues values;
 private int _id;

 public ButClickListenter(Context ctx, EditText n, EditText m, EditText r, int t ,int id){
 type = t;
 name = n;
 money = m;
 remark = r;
 mContext = ctx;
 dBbridge = new DBbridge(ctx);
 _id = id;

 }

 @Override
 public void onClick(View v) {
 switch (type){
 case 1:
 Log.i(TAG,"save");
 if(!checkField("项目名称不能为空",name.getText().toString())){
 break;
 }

 if(!checkField("请填写金额",money.getText().toString())){
 break;
 }


 values = new ContentValues();
 values.put("name",name.getText().toString());
 values.put("money",money.getText().toString());
 values.put("remark",remark.getText().toString().isEmpty() ? "无": remark.getText().toString());
 values.put("add_time",new Date().getTime());
 if(dBbridge.insert("account",values)>0){
 Toast.makeText(mContext,"保存成功!",Toast.LENGTH_LONG).show();
 clearEdit();
 }else{
 Toast.makeText(mContext,"保存失败!",Toast.LENGTH_LONG).show();
 }
 break;
 case 2:
 Log.i(TAG,"update");
 if(!checkField("项目名称不能为空",name.getText().toString())){
 break;
 }

 if(!checkField("请填写金额",money.getText().toString())){
 break;
 }

 if(_id<=0){
 Toast.makeText(mContext,"参数错误!",Toast.LENGTH_LONG).show();
 break;
 }
 values = new ContentValues();
 values.put("name",name.getText().toString());
 values.put("money",money.getText().toString());
 values.put("remark",remark.getText().toString().isEmpty() ? "无": remark.getText().toString());
 int res = dBbridge.update("account",values,"id=?",new String[]{String.valueOf(_id)});
 Log.i(TAG,String.valueOf(res));
 if(res > 0){
 Toast.makeText(mContext,"更新成功!",Toast.LENGTH_LONG).show();
 clearEdit();
 }else{
 Toast.makeText(mContext,"更新失败!",Toast.LENGTH_LONG).show();
 }

 break;
 case 3:
 Log.i(TAG,"delete");
 if(_id<=0){
 Toast.makeText(mContext,"参数错误!",Toast.LENGTH_LONG).show();
 break;
 }

 if(dBbridge.delete("account","id=?",new String[]{String.valueOf(_id)}) > 0){
 Toast.makeText(mContext,"删除成功!",Toast.LENGTH_LONG).show();
 clearEdit();
 }else{
 Toast.makeText(mContext,"删除失败!",Toast.LENGTH_LONG).show();
 }
 break;
 default:
 Log.i(TAG,"Nothing");
 break;
 }



 }

 public boolean checkField(String filed,String val){
 if(val.isEmpty() || val.trim().equals("")){
 Toast.makeText(mContext,filed,Toast.LENGTH_LONG).show();
 return false;
 }
 return true;
 }
 private void clearEdit(){
 name.setText("");
 money.setText("");
 remark.setText("");
 }
}

DBbridge.class源码
package com.test.sqlitetest;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Alan on 2016/05/13 0013.
 */
public class DBbridge {

 private Context mContext;
 private SQLiteDatabase db;
 private DBHelper dbHelper;

 public static final String DB_NAME = "db_account.db";
 public static final int DB_VERSION = 1;

 public DBbridge(Context ctx){
 mContext = ctx;
 dbHelper = new DBHelper(mContext,DB_NAME,null,DB_VERSION);
 db = dbHelper.getReadableDatabase();
 }

 /**
 * 插入数据
 * @param table 表名
 * @param values 要插入的数据对象
 * @return 返回-1则失败
 */
 public long insert(String table , ContentValues values){
 return db.insert(table,null,values);
 }

 /**
 * 修改数据
 * @param table 表名
 * @param values 要更新的数据对象
 * @param where 条件,如: id=? 或者 id=? and name like ?
 * @param whereArgs 条件对应数组值 new String[] {"1"} 或者 new String[] {"1","admin"}
 * @return
 */
 public int update(String table ,ContentValues values ,String where , String[] whereArgs){
 return db.update(table, values, where, whereArgs);
 }

 /**
 *删除数据
 * @param table 表名
 * @param where 条件,如: id=? 或者 id=? and name like ?
 * @param whereArgs 条件对应数组值 new String[] {"1"} 或者 new String[] {"1","admin"}
 * @return
 */
 public int delete(String table , String where , String[] whereArgs){
 return db.delete(table, where, whereArgs);
 }

 /**
 * 查询数据
 * @param table 表名
 * @param cls 列字段名
 * @param select 条件,如: id=? 或者 id=? and name like ?
 * @param selectionArgs 条件对应数组值 new String[] {"1"} 或者 new String[] {"1","admin"}
 * @param groupBy 分组
 * @param orderBy 排序
 * @return
 */
 public Cursor query(String table, String[] cls, String select, String[] selectionArgs, String groupBy, String orderBy, String limit){
 if(orderBy == null || orderBy.isEmpty()){
 orderBy = "id desc";
 }
 if(limit == null || limit.isEmpty()){
 limit = "0,30";
 }

 return db.query(table, cls, select, selectionArgs, groupBy, null, orderBy, limit);
 }

 public void execSQL(String sql){
 db.execSQL(sql);
 }

 public int getVersion(){
 return db.getVersion();
 }


 public class DBHelper extends SQLiteOpenHelper {
 private static final String CREATE_DB_SQL = "CREATE TABLE account (id INTEGER PRIMARY KEY autoincrement,name TEXT NOT NULL,money NUMERIC,remark TEXT,add_time long);";
 private static final String UPDATE_DB_SQL = "";

 public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
 super(context, name, factory, version);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
 db.execSQL(CREATE_DB_SQL);
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 db.execSQL(UPDATE_DB_SQL);
 }
 }


}

MenuSelect.class类源码
package com.test.sqlitetest;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Created by Alanon 2016/05/13 0013.
 */
public class MenuSelect {
    private static final String TAG = "MenuSelectLOG";
    private Context mContext;
    private MenuItem mItem;
    private DBbridge dBbridge;
    private Cursor cursor;
    private Intent intent;
    private Bundle bundle;

    public MenuSelect(Context ctx,MenuItem item){
        mContext = ctx;
        mItem = item;
    }

    public void setMenuOnSelectedListenter(){
        int id = mItem.getItemId();
        switch (id){
            case R.id.action_settings:
                Log.i(TAG,"action_settings");
                break;
            case R.id.action_list:
                Log.i(TAG,"action_list");
                dBbridge = new DBbridge(mContext);
                cursor = dBbridge.query("account",new String[]{"id","name","money","remark","add_time"},null,null,null,null,null);
                bundle = new Bundle();
                bundle.putSerializable("data",_makeObjToList(cursor));
                intent = new Intent(mContext,ListViewActivity.class);
                intent.putExtras(bundle);

                mContext.startActivity(intent);
                break;
            default:
                Log.i(TAG,"Nothing");
                break;
        }
    }

    protected ArrayList<Map<String,String>> _makeObjToList(Cursor cs){
        ArrayList<Map<String,String>> res = new ArrayList<Map<String,String>>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);

        while (cs.moveToNext()){
            Map<String,String> item = new HashMap<String,String>();
            item.put("id",cs.getString(0));
            item.put("name",cs.getString(1));
            item.put("money_ex","¥"+cs.getString(2));
            item.put("money",cs.getString(2));
            item.put("remark",cs.getString(3));
            item.put("add_time",df.format(new Date(Long.valueOf(cs.getString(4)))));
            res.add(item);
        }
        return res;
    }

}

 

ListViewActivity.class类源码片段
private void init(Context mContext) {
 listView = (ListView)findViewById(R.id.list0);

 registerForContextMenu(listView);

 ids = new int[]{R.id.list_id, R.id.list_name, R.id.list_money, R.id.list_remark, R.id.list_time};
 strs = new String[]{"id","name","money_ex","remark","add_time"};

 list = (List<Map<String,String>>) bundle.getSerializable("data");
 adapter = new SimpleAdapter(ListViewActivity.this,list,R.layout.list_item,strs,ids);

 listView.setAdapter(adapter);

 count_money = 0;
 for(Map<String,String> item : list){
 Log.i(TAG,item.get("id"));
 count_money += Float.valueOf(item.get("money"));
 }

 setTitle(getTitle()+" 共(¥"+count_money+")");
 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 @Override
 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 ListView _listView = (ListView) parent;

 Intent intent = new Intent(ListViewActivity.this, MainActivity.class);
 intent.putExtras(getBundle(_listView,position));
 startActivity(intent);
 finish();

 }
 });

 listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
 @Override
 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
 ListView _listView = (ListView) parent;
 bundle = getBundle(_listView, position);
 _position = position;
 return false;
 }
 });

 

实现后的图片展示:

a001

2

 

 

 

源码下载链接: http://pan.baidu.com/s/1qYMkofM 密码: b1tm

Leave a Comment