添加依赖: compile 'org.greenrobot:greendao:2.2.1'
首先建一个模块,新建一个包,用来存放待会自动生成的类(代码)
然后,新建一个纯JAVA的依赖模块(具体操作,看文档):
新建一个JAVA类:
public class DaoCen {
public static void main(String[]args) throws IOException {
//1、建立数据库的表
Schema schema=new Schema(
1,//数据库的版本号
"com.example.administrator.greendaodemo.db"//要生存在哪个包下面,全路径
);
addStudent(schema);//添加表
try {
// 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,
// 此处你需要根据自己的情况更改输出目录(既之前创建的 java-gen)。
new DaoGenerator().generateAll(schema,"D:/android_aaaa/GreenDaoDemo/app/src/main/java");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addStudent(Schema schema){
//添加表并添加实体类的类名
Entity entity=schema.addEntity("Student");
//如果不设置表名,那么生成的表名和实体类的类名一样
entity.setTableName("student");//设置表名
//添加表的列:
entity.addIntProperty("score");//分数
//添加id主键
entity.addIdProperty().primaryKey().autoincrement();
entity.addStringProperty("name");//姓名
entity.addBooleanProperty("gender");//性别
entity.addStringProperty("number");
//用于保存对象
//entity.addByteArrayProperty("avart");
}
}
自定义一个类,继承Application,在清单文件中找到该类:
<application android:name=".app.App" ---------name属性的值为指定该类的位置 android:allowBackup="true"
把数据库操作对象进行封装:
public class App extends Application { public DaoSession DAO; public static App app; @Override public void onCreate() { super.onCreate(); app=this; DaoMaster.DevOpenHelper helper=new DaoMaster.DevOpenHelper( this, "db_green", null ); //获取访问数据库的对象 DAO=new DaoMaster(helper.getWritableDatabase()).newSession(); } }
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.greendaodemo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="4"
>
<Button
android:id="@+id/b1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="添加" />
<Button
android:id="@+id/b2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="删除" />
<Button
android:id="@+id/b3"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="修改" />
<Button
android:id="@+id/b4"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="查询" />
</LinearLayout>
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#8c7e7e"
android:dividerHeight="2dp"
android:listSelector="#e694df"
>
</ListView>
</LinearLayout>
ListView的子布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#100e0e"
android:text="姓名:"
/>
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="杨钰莹"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#100e0e"
android:layout_marginLeft="50dp"
android:text="分数:"
/>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="98"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#100e0e"
android:text="性别是男人?:"
/>
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#100e0e"
android:layout_marginLeft="20dp"
android:text="编号:"
/>
<TextView
android:id="@+id/tv4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1001"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#100e0e"
android:layout_marginLeft="20dp"
android:text="id:"
/>
<TextView
android:id="@+id/tv5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1001"
/>
</LinearLayout>
</LinearLayout>
Activity中的代码:
package com.example.administrator.greendaodemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.greendaodemo.app.App;
import com.example.administrator.greendaodemo.db.Student;
import java.util.ArrayList;
import java.util.List;
/**
* greendao
* ORM数据库框架的简单使用
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ListView listview;
private List<Student> students;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
findViewById(R.id.b1).setOnClickListener(this);
findViewById(R.id.b2).setOnClickListener(this);
findViewById(R.id.b3).setOnClickListener(this);
findViewById(R.id.b4).setOnClickListener(this);
listview = (ListView) findViewById(R.id.listview);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.b1:
insert();//增
break;
case R.id.b2:
delete();//删
break;
case R.id.b3:
update();//改
break;
case R.id.b4:
query();//查
break;
}
}
private void insert() {//增加数据
/* Student student = new Student();
student.setGender(true);
student.setName("唐伯虎");
student.setScore(96);
student.setNumber("9527");
long i=App.app.DAO.getStudentDao().insert(student);//插入一条数据
*/
List<Student>list=new ArrayList<>();
long time=System.currentTimeMillis();//当前时间
int j=0;
for(int i=0;i<1000;i++){
Student student = new Student();
student.setGender(false);
if(i<500){
student.setName("杨钰莹"+(i+1)+"号");
}else{
student.setName("莫妮卡"+(i-499)+"号");
}
student.setScore(60+i);
student.setNumber("1" + i);
list.add(student);
j=i;
}
//插入多条数据
App.app.DAO.getStudentDao().insertInTx(list);
Toast.makeText(getApplicationContext(),"添加"+(j+1)+"条数据所有时间为:"+(System.currentTimeMillis()-time)+"毫秒",Toast.LENGTH_LONG).show();
}
private void delete() {//删除数据
//根据条件(分数为96分)来删除满足条件的数据(记录)
/* App.app.DAO.getStudentDao().queryBuilder()
.where(StudentDao.Properties.Score.eq(96))
.buildDelete().executeDeleteWithoutDetachingEntities();
*/
//通过实体类删除,必须设置主键的值
/* Student student=new Student();
student.setId((long) 500);
App.app.DAO.getStudentDao().delete(student);*/
//通过主键(id)删除多条记录
List<Long>lists=new ArrayList<>();
for(long i=501;i<1000;i++){
lists.add(i);
}
//根据id集合删除
App.app.DAO.getStudentDao().deleteByKeyInTx(lists);
}
private void update() {//修改
/* Student student=new Student();
student.setId((long) 502);
student.setName("张曼玉");
student.setScore(250);
//根据id去更新一条记录(没有设置的属性,在表里面的数据对应的字段就为null)
App.app.DAO.getStudentDao().update(student);*/
//根据其他添加批量更新(修改)多条数据
/* List<Student>stus=App.app.DAO.getStudentDao()
.queryBuilder().where(
StudentDao.Properties.Score.le(560)//分数小于或者等于560的
).list();
for(Student student:stus){
student.setName("我的杨钰莹");
}
//批量更新
App.app.DAO.getStudentDao().updateInTx(stus);*/
//直接执行SQL语句(分数小于561并且大于552的数据,该名字为赵雅芝)
App.app.DAO.getDatabase().execSQL("update student set name='赵雅芝' where score>552");
}
private void query() {//查询
students = App.app.DAO.getStudentDao().loadAll();//查询所有
if (adapter == null) {
adapter = new MyAdapter();
listview.setAdapter(adapter);
}
adapter.notifyDataSetChanged();//通知控件更新显示的内容
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return students.size();
}
@Override
public Object getItem(int position) {
return students.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = View.inflate(parent.getContext(),R.layout.itme,null);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.tv1);
holder.tv2 = (TextView) convertView.findViewById(R.id.tv2);
holder.tv3 = (TextView) convertView.findViewById(R.id.tv3);
holder.tv4 = (TextView) convertView.findViewById(R.id.tv4);
holder.tv5 = (TextView) convertView.findViewById(R.id.tv5);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Student student = students.get(position);
holder.tv1.setText(student.getName());
holder.tv2.setText(student.getScore()+"");
holder.tv3.setText(student.getGender() + "");
holder.tv4.setText(student.getNumber() + "");
holder.tv5.setText(student.getId() + "");
return convertView;
}
class ViewHolder {
public TextView tv1, tv2, tv3, tv4, tv5;
}
}
}