app->build.gradle
apply plugin: 'org.greenrobot.greendao'
greendao {
schemaVersion 1//数据库版本号
daoPackage 'sc.myapp.db.greenDao'//设置DaoMaster、DaoSession、Dao包名
targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
}
dependencies {
implementation 'org.greenrobot:greendao:3.2.2'
implementation 'org.greenrobot:greendao-generator:3.2.2'
}
具体代码如下:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 26
defaultConfig {
applicationId "sc.myapp"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
//GreenDao数据库插件
greendao {
schemaVersion 1//数据库版本号
daoPackage 'sc.myapp.db.greenDao'//设置DaoMaster、DaoSession、Dao包名
targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
androidTestCompile('com.android.support:support-annotations:26.1.0') {
force = true
}
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'org.greenrobot:greendao:3.2.2'
implementation 'org.greenrobot:greendao-generator:3.2.2'
}
主工程下build.gradle
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
具体代码如下:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
创建一个实体类
@Entity
public class Login {
@Id(autoincrement = true)
private Long id;
private String userNo;
private String password;
}
Build–>Make Project或者Make Module ‘你的项目’
AS会在sc.myapp.db.green下自动创建DaoMaster,DaoSession,LoginDao
需要再创建DaoManager.java和LoginUtils.java工具类
DaoManager.java
/**
* 创建数据库、创建数据库表、包含增删改查的操作以及数据库的升级
*/
public class DaoManager {
private static final String TAG = DaoManager.class.getSimpleName();
private static final String DB_NAME = "login";
private Context context;
//多线程中要被共享的使用volatile关键字修饰
private volatile static DaoManager manager = new DaoManager();
private static DaoMaster sDaoMaster;
private static DaoMaster.DevOpenHelper sHelper;
private static DaoSession sDaoSession;
/**
* 单例模式获得操作数据库对象
* @return
*/
public static DaoManager getInstance(){
return manager;
}
public void init(Context context){
this.context = context;
}
/**
* 判断是否有存在数据库,如果没有则创建
* @return
*/
public DaoMaster getDaoMaster(){
if(sDaoMaster == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
sDaoMaster = new DaoMaster(helper.getWritableDatabase());
}
return sDaoMaster;
}
/**
* 完成对数据库的添加、删除、修改、查询操作,仅仅是一个接口
* @return
*/
public DaoSession getDaoSession(){
if(sDaoSession == null){
if(sDaoMaster == null){
sDaoMaster = getDaoMaster();
}
sDaoSession = sDaoMaster.newSession();
}
return sDaoSession;
}
/**
* 打开输出日志,默认关闭
*/
public void setDebug(){
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
/**
* 关闭所有的操作,数据库开启后,使用完毕要关闭
*/
public void closeConnection(){
closeHelper();
closeDaoSession();
}
public void closeHelper(){
if(sHelper != null){
sHelper.close();
sHelper = null;
}
}
public void closeDaoSession(){
if(sDaoSession != null){
sDaoSession.clear();
sDaoSession = null;
}
}
}
LoginUtils.java
public class LoginUtils {
private static final String TAG = LoginUtils.class.getSimpleName();
private DaoManager mManager;
public LoginUtils(Context context){
mManager = DaoManager.getInstance();
mManager.init(context);
}
/**
* 完成login记录的插入,如果表未创建,先创建Login表
* @param login
* @return
*/
public boolean insertLogin(Login login){
boolean flag = false;
flag = mManager.getDaoSession().getLoginDao().insert(login) == -1 ? false : true;
Log.i(TAG, "insert LoginDB :" + flag + "-->" + login.toString());
return flag;
}
/**
* 插入多条数据,在子线程操作
* @param loginList
* @return
*/
public boolean insertMultLogin(final List<Login> loginList) {
boolean flag = false;
try {
mManager.getDaoSession().runInTx(new Runnable() {
@Override
public void run() {
for (Login login : loginList) {
mManager.getDaoSession().insertOrReplace(login);
}
}
});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 修改一条数据
* @param login
* @return
*/
public boolean updateLogin(Login login){
boolean flag = false;
try {
mManager.getDaoSession().update(login);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
/**
* 删除单条记录
* @param login
* @return
*/
public boolean deleteLogin(Login login){
boolean flag = false;
try {
//按照id删除
mManager.getDaoSession().delete(login);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
/**
* 删除所有记录
* @return
*/
public boolean deleteAll(){
boolean flag = false;
try {
//按照id删除
mManager.getDaoSession().deleteAll(Login.class);
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
/**
* 查询所有记录
* @return
*/
public List<Login> queryAllLogin(){
return mManager.getDaoSession().loadAll(Login.class);
}
/**
* 根据主键id查询记录
* @param key
* @return
*/
public Login queryLoginById(long key){
return mManager.getDaoSession().load(Login.class, key);
}
/**
* 使用native sql进行查询操作
*/
public List<Login> queryLoginByNativeSql(String sql, String[] conditions){
return mManager.getDaoSession().queryRaw(Login.class, sql, conditions);
}
/**
* 使用queryBuilder进行查询
* @return
*/
public List<Login> queryLoginByQueryBuilderUserNo(String userNo){
QueryBuilder<Login> queryBuilder = mManager.getDaoSession().queryBuilder(Login.class);
return queryBuilder.where(LoginDao.Properties.UserNo.eq(userNo)).list();
}
public List<Login> queryLoginByQueryBuilderPassword(String password){
QueryBuilder<Login> queryBuilder = mManager.getDaoSession().queryBuilder(Login.class);
return queryBuilder.where(LoginDao.Properties.Password.eq(password)).list();
}
}
主要使用LoginUtils.java里的方法进行数据库操作
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private EditText userNo;
private EditText password;
private Button login;
private Button register;
private LoginUtils loginUtils=new LoginUtils(LoginActivity.this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
OnClick();
}
private void initView() {
userNo=findViewById(R.id.login_userNo);
password=findViewById(R.id.login_password);
login=findViewById(R.id.loginBtn);
register=findViewById(R.id.registerBtn);
}
private void OnClick() {
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (check()){
loginUtils.insertLogin(new Login(null,userNo.getText().toString(),
password.getText().toString()));
Toast.makeText(LoginActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
}
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (check()){
List<Login> list=loginUtils.queryLoginByQueryBuilderUserNo(userNo.getText().toString());
if (list==null){
Toast.makeText(LoginActivity.this,"账号不存在",Toast.LENGTH_SHORT).show();
}else {
boolean isSuccess=true;
for (Login login:list){
if (login.getUserNo().equals(userNo.getText().toString())&&login.getPassword().equals(password.getText().toString())){
Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
isSuccess=false;
}
}
if (isSuccess){
Toast.makeText(LoginActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
}
}
}
}
});
}
private boolean check() {
if (userNo.getText().toString()!=null&&password.getText().toString()!=null){
return true;
}else {
Toast.makeText(LoginActivity.this,"账号密码不能为空",Toast.LENGTH_SHORT).show();
}
return false;
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="sc.myapp.ui.LoginActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="账号:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/login_userNo"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="密码:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/login_password"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/loginBtn"
android:layout_weight="1"
android:text="登录"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/registerBtn"
android:layout_weight="1"
android:text="注册"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>