1,在项目的build.grade中
dependencies{
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
}
2,在app的build.grade
apply plugin: 'org.greenrobot.greendao'
3:在app的build.grad里面Android{}
greendao{
schemaVersion 1 //指定数据库schema版本号,迁移等操作会用到包名是活的这是变动的
daoPackage 'soexample.umeng.com.greendaodemo.mydao' //切换为你自己的包名
targetGenDir 'src/main/java' //生成数据库文件的目录
}
4,导入依赖
implementation 'org.greenrobot:greendao:3.2.2'
5,写一个实体类 并添加字段
@Entity
public class Person {
@Id(autoincrement = true) //主键自增
private Long id;
private String name;
private String sex;
}
6,点击make project得到三个class文件
通过锤子(make Project)
* 1:DaoMaster
* 2:DaoSession
* 3:PersonDao
7,创建一个类 继承Application
public class MyApp extends Application {
private static DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
initgreendao();
}
private void initgreendao() {
DaoMaster.DevOpenHelper openHelper=new DaoMaster.DevOpenHelper(this,"zpp.db");
SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
DaoMaster master=new DaoMaster(writableDatabase);
daoSession = master.newSession();
}
public static DaoSession getDaoSession(){
return daoSession;
}
}
不要忘记在manifest中
android:name=".MyApp"
8,最后增删改查 四个按钮
public class MainActivity extends AppCompatActivity {
@BindView(R.id.zeng)
Button zeng;
@BindView(R.id.shan)
Button shan;
@BindView(R.id.gai)
Button gai;
@BindView(R.id.cha)
Button cha;
@BindView(R.id.tv)
TextView tv;
private PersonDao mDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mDao = MyApp.getDaoSession().getPersonDao();
}
@OnClick({R.id.zeng, R.id.shan, R.id.gai, R.id.cha})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.zeng:
insertstr();
break;
case R.id.shan:
delStr();
break;
case R.id.gai:
updata();
break;
case R.id.cha:
selectstr();
break;
}
}
//改
private void updata() {
Person person = mDao.load(3l);
person.setName("张三");
person.setSex("女");
mDao.update(person);
}
//删
private void delStr() {
mDao.deleteByKey(1l);
Toast.makeText(MainActivity.this,"删除成功!",Toast.LENGTH_LONG).show();
}
//查
private void selectstr() {
tv.setText("");
List<Person> people = mDao.loadAll();
tv.setText(people.toString());
}
//增
private void insertstr() {
Person person = new Person("哈哈哈", "男");
long insert = mDao.insert(person);
if (insert > 0) {
Toast.makeText(MainActivity.this, "添加成功!", Toast.LENGTH_LONG).show();
}
}
}