开发日志(2)——Bean目录以及数据库
首先编写一些自己生成的数据进行测试,看一下能否显示在模拟器上。那前提就是先写出bean目录,这和之前学的Javaweb步骤差不多。bean目录有三个变量事件、时间、花费。所以bean目录很容易就写出
CostBean
package com.example.firstapplication; import java.io.Serializable; public class CostBean implements Serializable { public String costTitle; public String costDate; public String costMoney; }
这里面的implements Serializable是之后将数据传给线性表时添加的。一个类只有实现了Serializable接口,它的对象才是可序列化的。因此如果要序列化某些类的对象,这些类就必须实现Serializable接口。而实际上,Serializable是一个空接口,没有什么具体内容,它的目的只是简单的标识一个类的对象可以被序列化。
既然是个记账本,那里面的数据肯定不能丢失,不能出现关机了或者程序退出了数据就消失的现象。所以我们得写一个数据库,将数据保存下来
下面是对数据库进行增删改查操作的sql语句
增:(add)
db.execSQL("insert into Users (username,password) values(?,?)",new Object[]{bean.username,bean.password});
删:(delete)
db.execSQL("delete from Users where username=?",new String[]{username});
改:(update)
db.execSQL("update Users set password=? where username=?",new Object[]{bean.password,bean.username});
查:(select)
Cursor c=db.rawQuery("select * from Users where username=?",new String[]{name});
Cursor c=db.rawQuery("select * from Users",null);
数据库类
DatabaseHelper:
package com.example.firstapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class DatabaseHelper extends SQLiteOpenHelper { public static final String COST_TITLE = "cost_title"; public static final String COST_DATE = "cost_date"; public static final String COST_MONEY = "cost_money"; public static final String IMOOC_COST = "imooc_cost"; public DatabaseHelper(Context context) { super(context, "imooc_daily", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table if not exists imooc_cost(" + "id integer primary key," + "cost_title varchar," + "cost_date varchar ," + "cost_money varchar)" ); } public void insertCost(CostBean costBean){ SQLiteDatabase database = getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COST_TITLE,costBean.costTitle); cv.put(COST_DATE,costBean.costDate); cv.put(COST_MONEY,costBean.costMoney); database.insert(IMOOC_COST,null,cv); } public Cursor getAllCostData(){ SQLiteDatabase database = getWritableDatabase(); return database.query(IMOOC_COST,null,null,null,null,null,"cost_date ASC"); } public void deleteAlldata(){ SQLiteDatabase database = getWritableDatabase(); database.delete(IMOOC_COST,null,null); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void deleteOne(CostBean costBean) { SQLiteDatabase database=getWritableDatabase(); database.delete(IMOOC_COST,"COST_TITLE = ? and COST_MONEY = ? and COST_DATE = ?", new String[]{""+costBean.costTitle,""+costBean.costMoney,""+costBean.costDate}); } }
接下来就可以在Activity中调用了,将数据保存到数据库中
明天准备生成点数据,编写一下MainActivity,将数据显示出来