在android Studio2 项目中增加greendao 引用。
1、新增加一个项目,在App文件夹中的build.gradle 增加如下配置信息
buildscript { repositories { mavenCentral() } dependencies { classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0' } }
apply plugin: 'org.greenrobot.greendao'
dependencies { ...... compile 'org.greenrobot:greendao:3.1.0' } greendao { targetGenDir 'src/main/java' }
2、点击 Sync Project with Gradle Files ,同步greendao 第三方库
3、增加实体类文件
@Entity public class User { @Id(autoincrement = true) private Long id;
public Long getId() { return id; } public void setId(Long id) { this.id = id; }}
4、重新编辑项目,会在实体类包下生成 DaoMaster、DaoSession、UserDao 3个类文件,通过这3各类就可以实现数据库操作。
5、可以参看下面代码实现数据的操作。
public class DBManager { private final static String dbName = "test_db"; private static DBManager mInstance; private DaoMaster.DevOpenHelper openHelper; private Context context; public DBManager(Context context) { this.context = context; openHelper = new DaoMaster.DevOpenHelper(context, dbName, null); } /** * 获取单例引用 * * @param context * @return */ public static DBManager getInstance(Context context) { if (mInstance == null) { synchronized (DBManager.class) { if (mInstance == null) { mInstance = new DBManager(context); } } } return mInstance; } /** * 获取可写数据库 */ private SQLiteDatabase getWritableDatabase() { if (openHelper == null) { openHelper = new DaoMaster.DevOpenHelper(context, dbName, null); } SQLiteDatabase db = openHelper.getWritableDatabase(); return db; } public void insertUser(User user) { DaoMaster daoMaster = new DaoMaster(getWritableDatabase()); DaoSession daoSession = daoMaster.newSession(); UserDao userDao = daoSession.getUserDao(); userDao.insertOrReplace(user); } /** * 获取可读数据库 */ private SQLiteDatabase getReadableDatabase() { if (openHelper == null) { openHelper = new DaoMaster.DevOpenHelper(context, dbName, null); } SQLiteDatabase db = openHelper.getReadableDatabase(); return db; } /** * 查询用户列表 */ public List<User> queryUserList() { DaoMaster daoMaster = new DaoMaster(getReadableDatabase()); DaoSession daoSession = daoMaster.newSession(); UserDao userDao = daoSession.getUserDao(); QueryBuilder<User> qb = userDao.queryBuilder(); List<User> list = qb.list(); return list; } }