效果图:

 

项目目录截图:

1、activity_main.xml

  描述:

    两行显示8个按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="添加用户"
android:onClick="addUser"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="查询用户"
android:onClick="findUserList"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="删除用户"
android:onClick="deleteUser"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="修改用户"
android:onClick="updateUser"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout> <LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="添加部门"
android:onClick="addDept"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="查询部门"
android:onClick="findDeptList"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="添加员工"
android:onClick="addEmp"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="查询员工"
android:onClick="findEmpList"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>

2、MainActivity.java

package com.nf.android_ormlite;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast; import com.nf.dao.DeptDao;
import com.nf.dao.EmpDao;
import com.nf.dao.UsersDao;
import com.nf.entity.TbDept;
import com.nf.entity.TbEmp;
import com.nf.entity.Users; import java.sql.SQLException;
import java.util.Date;
import java.util.List; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//添加用户操作
//new一个Users将用户的编号、用户名、密码、日期封装起来交给UsersDao里的addUsers()方法进行添加用户的操作
//添加成功返回结果并弹出提示
public void addUser(View view) throws SQLException {
boolean res=new UsersDao(this).addUsers(new Users(0,"abc","123123",new Date()));
Toast.makeText(this, "添加用户结果是:"+res, Toast.LENGTH_SHORT).show();
}
//查询用户信息列表的操作
//调用UsersDao里的getUserList()方法从数据库中获取到所有用户的信息,保存到list集合中
public void findUserList(View view) throws SQLException {
List<Users> users=new UsersDao(this).getUserList();
//对list集合进行循环遍历,取出用户编号、用户名称、用户密码写入日志中
for (Users user:users){
Log.i("FindUserList:",user.get_id()+","+user.getUname()+","+user.getUpwd());
}
}
//根据用户ID删除用户信息的操作
//调用UserDao中的deleteUsers()方法传入一个用户ID,删除该ID对应的用户信息
public void deleteUser(View view) throws SQLException {
UsersDao dao=new UsersDao(this);
Users user=dao.getUserById(3);
boolean res=new UsersDao(this).deleteUsers(user);
Toast.makeText(this, "删除用户结果是:"+res, Toast.LENGTH_SHORT).show();
}
//修改用户信息的操作
//调用UserDao的updateUsers()方法将编号为2的用户的用户名称修改为Toms
public void updateUser(View view) throws SQLException { UsersDao dao=new UsersDao(this);
Users user=dao.getUserById(2);
user.setUname("Toms");
boolean res=dao.updateUsers(user);
Toast.makeText(this, "修改用户结果是:"+res, Toast.LENGTH_SHORT).show();
}
//添加部门的操作
//调用DeptDaod的addDept()方法添加一个学工部
public void addDept(View view) throws SQLException {
TbDept dept=new TbDept(0,"学工部");
new DeptDao(this).addDept(dept);
Toast.makeText(this, "添加部门成功", Toast.LENGTH_SHORT).show();
}
//查询部门的操作
//调用DeptDao的findDeptList()方法从数据库中获取所有的部门信息放入list集合中
public void findDeptList(View view) throws SQLException {中心
List<TbDept> list=new DeptDao(this).findDeptList();
//对list集合进行循环遍历,获取出部门编号、部门名称、该部门员工的人数
for(TbDept dept:list){
Log.i("DeptList:",dept.get_id()+","+dept.getDname()+","+dept.getEmps().size());
}
}
//添加员工的操作
//调用TbEmp()实体对象封装一名员工信息
//再调用EmpDao中的addEmp()方法将员工信息添加到数据库
//我们在员工表里再绑定他所在的部门
public void addEmp(View view) throws SQLException {
TbEmp emp=new TbEmp(0,"Kite",22,"男");
//取出学术部
TbDept dept=new DeptDao(this).getDeptById(2);
//绑定员工和部门
emp.setDept(dept);
//保存员工
new EmpDao(this).addEmp(emp);
Toast.makeText(this, "添加员工成功", Toast.LENGTH_SHORT).show();
}
//查询员工信息的操作
//调用EmpDao中的findempList()方法从数据库中查询出来放入list集合
public void findEmpList(View v) throws Exception{
List<TbEmp> emps=new EmpDao(this).findEmpList();
//退list集合进行循环遍历,查询出所有员工的编号、姓名、部门名称
for (TbEmp emp:emps){
Log.i("EmpList:",emp.get_id()+","+emp.getEname()+","+emp.getDept().getDname());
}
}
}

3、dao/DeptDao.java

package com.nf.dao;
import android.content.Context; import com.nf.entity.TbDept;
import com.nf.utils.DbHelper; import java.sql.SQLException;
import java.util.List; public class DeptDao { private DbHelper dbHelper;
public DeptDao(Context context){
     //实例化DbHelper
dbHelper=DbHelper.getInstance(context);
} public boolean addDept(TbDept dept) throws SQLException {
     //通过dbHelper调用getDaos()
dbHelper.getDaos(TbDept.class).create(dept);
return true;
} public List findDeptList() throws SQLException {
return dbHelper.getDaos(TbDept.class).queryForAll();
} public TbDept getDeptById(int id) throws SQLException {
return (TbDept) dbHelper.getDaos(TbDept.class).queryForId(id);
}
}

4、dao/EmpDao.java

package com.nf.dao;
import android.content.Context; import com.nf.entity.TbEmp;
import com.nf.utils.DbHelper; import java.sql.SQLException;
import java.util.List; /**
* Created by Administrator on 2017/12/13.
*/ public class EmpDao { private DbHelper dbHelper;
public EmpDao(Context context){
dbHelper=DbHelper.getInstance(context);
} public boolean addEmp(TbEmp emp) throws SQLException {
dbHelper.getDaos(TbEmp.class).create(emp);
return true;
} public List findEmpList() throws SQLException {
return dbHelper.getDaos(TbEmp.class).queryForAll();
}
}

5、dao/UsersDao.java

package com.nf.dao;
import android.content.Context; import com.nf.entity.Users;
import com.nf.utils.DbHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder; import java.sql.SQLException;
import java.util.List; /**
* Created by Administrator on 2017/12/13.
*/ public class UsersDao { private DbHelper dbHelper;
private Dao dao;//DbHelper对象提供的一个对象持久化类
public UsersDao(Context context){
dbHelper=new DbHelper(context);
try {
dao=dbHelper.getDao(Users.class);
} catch (SQLException e) {
e.printStackTrace();
}
} //添加一个用户
public boolean addUsers(Users user) throws SQLException {
dao.create(user);
return true;
} //修改一个用户
public boolean updateUsers(Users user) throws SQLException {
dao.update(user);
return true;
} //删除一个用户
public boolean deleteUsers(Users user) throws SQLException {
dao.delete(user);
return true;
} public Users getUserById(int id) throws SQLException {
Users user=(Users) dao.queryForId(id);
return user;
} public List getUserList() throws SQLException {
List list=dao.queryForAll();
return list;
} //==============批量操作=============//
public boolean addUsers(List<Users> users) throws SQLException {
dao.create(users);
return true;
}
public boolean deleteUsers(List<Users> users) throws SQLException {
dao.delete(users);
return true;
} //==============带条件修改删除查询=============//
public boolean updateUsersByPwd(String query) throws SQLException {
UpdateBuilder builder=dao.updateBuilder();
builder.where().like("upwd",query);
builder.updateColumnValue("upwd","123456");
builder.update();
return true;
} public boolean deleteUsers(String name) throws SQLException {
DeleteBuilder builder=dao.deleteBuilder();
builder.where().eq("uname",name);
builder.delete();
return true;
}
public List findUserList(String name) throws SQLException {
QueryBuilder builder=dao.queryBuilder();
builder.where().like("uname","%"+name+"%");
builder.orderBy("uintime",true);
List list=builder.query();
return list;
}
}

6、entity/TbDept.java

package com.nf.entity;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; @DatabaseTable(tableName = "tb_dept") //通过注解的方式设置部门表的表名
public class TbDept implements Serializable { @DatabaseField(generatedId = true)//设置部门编号 generatedId = true表示编号自动增长
private int _id;
@DatabaseField //默认设置
private String dname; //一对多的关系
@ForeignCollectionField(eager = false)
private ForeignCollection<TbEmp> emps; public TbDept() {
} public TbDept(int _id, String dname) {
this._id = _id;
this.dname = dname;
} public int get_id() {
return _id;
} public void set_id(int _id) {
this._id = _id;
} public String getDname() {
return dname;
} public void setDname(String dname) {
this.dname = dname;
} public ForeignCollection<TbEmp> getEmps() {
return emps;
} public void setEmps(ForeignCollection<TbEmp> emps) {
this.emps = emps;
}
}

7、entity/TbEmp.java

package com.nf.entity;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable;
//指定表名称
@DatabaseTable(tableName = "tb_emp")
public class TbEmp implements Serializable { @DatabaseField(generatedId = true)
private int _id;
@DatabaseField
private String ename;
@DatabaseField
private int eage;
@DatabaseField
private String esex; //多对一的关系
@DatabaseField(columnName = "edno",foreign = true,foreignAutoRefresh = true,canBeNull = false)
private TbDept dept; public TbEmp() {
} public TbEmp(int _id, String ename, int eage, String esex) {
this._id = _id;
this.ename = ename;
this.eage = eage;
this.esex = esex;
} public int get_id() {
return _id;
} public void set_id(int _id) {
this._id = _id;
} public String getEname() {
return ename;
} public void setEname(String ename) {
this.ename = ename;
} public int getEage() {
return eage;
} public void setEage(int eage) {
this.eage = eage;
} public String getEsex() {
return esex;
} public void setEsex(String esex) {
this.esex = esex;
} public TbDept getDept() {
return dept;
} public void setDept(TbDept dept) {
this.dept = dept;
}
}

8、entity/Users.java

package com.nf.entity;

import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable;
import java.util.Date; /**
* Created by Administrator on 2017/12/13.
*/
@DatabaseTable(tableName = "tb_users")
public class Users implements Serializable{
   //指定该字段为主键且自动增长
@DatabaseField(generatedId = true)
private int _id;
   //指定字段不能为空
@DatabaseField(canBeNull = false)
private String uname;
@DatabaseField(canBeNull = false)
private String upwd;
@DatabaseField(dataType = DataType.DATE)
private Date uintime; public Users() {
} public Users(int _id, String uname, String upwd, Date uintime) {
this._id = _id;
this.uname = uname;
this.upwd = upwd;
this.uintime = uintime;
} public int get_id() {
return _id;
} public void set_id(int _id) {
this._id = _id;
} public String getUname() {
return uname;
} public void setUname(String uname) {
this.uname = uname;
} public String getUpwd() {
return upwd;
} public void setUpwd(String upwd) {
this.upwd = upwd;
} public Date getUintime() {
return uintime;
} public void setUintime(Date uintime) {
this.uintime = uintime;
}
}

9、DbHelper.java

package com.nf.utils;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast; import com.nf.entity.TbDept;
import com.nf.entity.TbEmp;
import com.nf.entity.Users;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils; import java.util.Date;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
//构建一个DbHelper类继承OrmLiteSqliteOpenHelper 实现对数据库的操作
public class DbHelper extends OrmLiteSqliteOpenHelper {
//定义数据库名称
private static final String DATABASE_NAME="ormlite.db";
//定义数据库的版本
private static final int VERSION=3;
//构造器,将上下文对象、数据库名称、工厂、版本信息初始化
public DbHelper(Context context) {//用于通过注解+反射创建数据库表
super(context, DATABASE_NAME, null, VERSION);//用于通过读取配置文件创建数据库表
}
private DbHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion) {
super(context, DATABASE_NAME, null, VERSION);
} //第一次创建数据库时执行
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
//创建表Tb_users
TableUtils.createTableIfNotExists(connectionSource, Users.class);
//创建表Tb_dept
TableUtils.createTableIfNotExists(connectionSource, TbDept.class);
//创建表Tb_emp
TableUtils.createTableIfNotExists(connectionSource, TbEmp.class);
} catch (SQLException e) {
e.printStackTrace();
} //加入测试数据
try {
//调用Dao中的getDao()方法传入一个实体对象,实体对象里封装一个用户,通过create()方法,将这个用户初始化到tb_users数据表中
Dao dao=getDao(Users.class);//创建一个Users类的Dao
dao.create(new Users(0,"admins","admins",new Date()));
} catch (SQLException e) {
e.printStackTrace();
}
Log.i("create table","创建数据表成功");
} @Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource,Users.class,true);
TableUtils.dropTable(connectionSource,TbEmp.class,true);
TableUtils.dropTable(connectionSource,TbDept.class,true);
onCreate(database,connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
} //===================提供单例模式DbHelper对象提供服务=========================//
private static DbHelper dbHelper; public static synchronized DbHelper getInstance(Context context){
if(dbHelper==null){
dbHelper=new DbHelper(context);
}
return dbHelper;
} //==================构建一个Dao栈,统一管理Dao=======================//
private Map<String,Dao> daos=new HashMap<String,Dao>(); public Dao getDaos(Class cls) throws SQLException {
String className=cls.getName();//获取类名
if(!daos.containsKey(className)){
daos.put(className,super.getDao(cls));
}
return daos.get(className);
} //重写DbHelper的close方法
@Override
public void close() {
super.close();
Iterator it=daos.keySet().iterator();
while(it.hasNext()){
Dao dao=(Dao) it.next();
dao=null;
}
}
}

Android开发 ---ORMLite实现数据的增删改查,单例模式,Dao栈的更多相关文章

  1. 三年Android开发,竟只会增删改查,被面试官一顿怼!

    最近看到某公司面试官发的这样一个帖子: 我面试了一个有三年Android开发经验的小伙子,也是我有史以来给别人面试时间最短的一次,不到十分钟就结束了,原因很简单,底子太差只会curd,很多技术性的问题 ...

  2. Mybatis框架基于注解的方式,实对数据现增删改查

    编写Mybatis代码,与spring不一样,不需要导入插件,只需导入架包即可: 在lib下 导入mybatis架包:mybatis-3.1.1.jarmysql驱动架包:mysql-connecto ...

  3. python 全栈开发,Day124(MongoDB初识,增删改查操作,数据类型,$关键字以及$修改器,"$"的奇妙用法,Array Object 的特殊操作,选取跳过排序,客户端操作)

    一.MongoDB初识 什么是MongoDB MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介 ...

  4. django学习-12.访问不同url/接口地址实现对指定数据的增删改查功能

    1.前言 通过前面博客[django学习-10.django连接mysql数据库和创建数据表]里的操作,我们已经成功在数据库[hongjingsheng_project]里创建了一张数据表[hello ...

  5. Android 系统API实现数据库的增删改查和SQLite3工具的使用

    在<Android SQL语句实现数据库的增删改查>中介绍了使用sql语句来实现数据库的增删改查操作,本文介绍Android 系统API实现数据库的增删改查和SQLite3工具的使用. 系 ...

  6. dbutils中实现数据的增删改查的方法,反射常用的方法,绝对路径的写法(杂记)

    jsp的三个指令为:page,include,taglib... 建立一个jsp文件,建立起绝对路径,使用时,其他jsp文件导入即可 导入方法:<%@ include file="/c ...

  7. MVC模式:实现数据库中数据的增删改查功能

    *.数据库连接池c3p0,连接mysql数据库: *.Jquery使用,删除时跳出框,确定是否要删除: *.使用EL和JSTL,简化在jsp页面中插入的java语言 1.连接数据库 (1)导入连接数据 ...

  8. Hibernate3回顾-5-简单介绍Hibernate session对数据的增删改查

    5. Hibernate对数据的增删改查 5.1Hibernate加载数据 两种:get().load() 一. Session.get(Class arg0, Serializable arg1)方 ...

  9. Mybatis学习总结(二)—使用接口实现数据的增删改查

    在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num ...

随机推荐

  1. [ Build Tools ] Repositories

    仓库介绍 http://hao.jobbole.com/central-repository/ https://my.oschina.net/pingjiangyetan/blog/423380 ht ...

  2. meterpreter 渗透用法

    获取凭证 hashdump模块(post)可以从SAM数据库中导出本地用户账号,credential_collector脚本(post/windows/gather/credentials)也可以从目 ...

  3. 使用 Docker 搭建 Java Web 运行环境(转)

    原文 http://www.importnew.com/21798.html Docker 是 2014 年最为火爆的技术之一,几乎所有的程序员都听说过它.Docker 是一种“轻量级”容器技术,它几 ...

  4. [openjudge-搜索]单词接龙

    题目描述 描述 单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的"龙"(每个单词都最多在"龙&q ...

  5. Java try和catch的使用介绍

    尽管由Java运行时系统提供的默认异常处理程序对于调试是很有用的,但通常你希望自己处理异常.这样做有两个好处.第一,它允许你修正错误.第二,它防止程序自动终止.大多数用户对于在程序终止运行和在无论何时 ...

  6. 用java生成32位全球唯一的id编号

    GUID是一个128位长的数字,一般用16进制表示.算法的核心思想是结合机器的网卡.当地时间.一个随即数来生成GUID.从理论上讲,如果一台机器每秒产生10000000个GUID,则可以保证(概率意义 ...

  7. python爬虫——论抓包的正确姿势和学好Javascript的重要性(1)

    没事想爬下数据,就入了scrapy坑,跟着https://zhuanlan.zhihu.com/data-factory这篇教程走,中间被小数量的网站坑过,不过还是写出了爬虫~~ 切糕王子:毫无防御, ...

  8. JSOIWC2019游记

    世除我WC...都去广二了qaq,就我还在nj ycs至少也去了pkuwc啊 这个JSOIWC2019的内容看起来很水,进入条件简单,但窝啥都不会,肯定垫底 内容清单: 1.26 上午听机房dalao ...

  9. Codeforces 528E Triangles 3000 - 计算几何

    题目传送门 传送点I 传送点II 传送点III 题目大意 给定$n$的平面上的直线,保证没有三条直线共点,两条直线平行.问随机选出3条直线交成的三角形面积的期望. 显然$S=\frac{1}{2}ah ...

  10. Bumped!【最短路】(神坑

    问题 B: Bumped! 时间限制: 1 Sec  内存限制: 128 MB 提交: 351  解决: 44 [提交] [状态] [命题人:admin] 题目描述 Peter returned fr ...