家庭记账本3
今天主要书写dao层的内容
MoneyDao.java
package com.example.money; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; public class MoneyDao { private DatabaseHelper databaseHelper; public MoneyDao(Context context){ databaseHelper = new DatabaseHelper(context); } //插入操作 public void insert(String money,String date,String title,String type){ //开启数据库,准备做写入操作 SQLiteDatabase db=databaseHelper.getWritableDatabase(); //创建ContentValues对象封装键值对 ContentValues values=new ContentValues(); //要插入的字段名和字段值 values.put("money",money); values.put("date",date); values.put("title",title); values.put("type",type); //插入数据(表名,字段没有值时把字段维护成null,内容值) db.insert("information",null,values); //关闭数据库 db.close(); } //删除操作 public void delete(String money){ //开启数据库, SQLiteDatabase db=databaseHelper.getWritableDatabase(); //删除数据(表名,要删除的字段,传入要删除的内容具体值 ) db.delete("information","money=?",new String[]{money}); //关闭数据库 db.close(); } public List<MoneyInfo> findAll(){ //开启数据库 SQLiteDatabase db=databaseHelper.getWritableDatabase(); //查询所有数据 Cursor cursor=db.query("information",new String[]{"money","date","title","type"},null,null,null,null,"_id desc"); List<MoneyInfo> moneyInfoList=new ArrayList<>(); //如果游标能往下移动 while (cursor.moveToNext()){ MoneyInfo moneyInfo=new MoneyInfo(); //游标每向下移动一次,就获取索引为0,索引为1的字段(也就是phone字段和mode字段)赋值给BlackNumberInfo对象 moneyInfo.setMoney(cursor.getString(0)); moneyInfo.setDate(cursor.getString(1)); moneyInfo.setTitle(cursor.getString(2)); moneyInfo.setType(cursor.getString(3)); //把MoneyInfo添加到集合中 moneyInfoList.add(moneyInfo); } cursor.close(); //关闭数据库 db.close(); return moneyInfoList; } }