├── settings.gradle
├── pic
└── 1.jpg
├── easydb
├── AndroidPlugins.jar
├── src
│ └── main
│ │ ├── res
│ │ └── values
│ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── easydblib
│ │ ├── callback
│ │ ├── EasyRunAbs.java
│ │ ├── IUpgrade.java
│ │ └── EasyRun.java
│ │ ├── annotation
│ │ └── TableModel.java
│ │ ├── handler
│ │ ├── MessageInfo.java
│ │ ├── HandlerHelper.java
│ │ └── EasyDBProxyHandler.java
│ │ ├── info
│ │ ├── OrderInfo.java
│ │ ├── Result.java
│ │ ├── Where.java
│ │ └── WhereInfo.java
│ │ ├── util
│ │ ├── CheckUtil.java
│ │ └── CastUtil.java
│ │ ├── EasyDBConfig.java
│ │ ├── helper
│ │ ├── DatabaseSDContext.java
│ │ ├── DBHelper.java
│ │ ├── BaseDBHelper.java
│ │ └── DBBuilder.java
│ │ └── dao
│ │ ├── DBDao.java
│ │ ├── RealBaseDao.java
│ │ ├── BaseDaoImp.java
│ │ └── RealBaseDaoImpl.java
├── build.gradle
└── bintrayUpload.gradle
├── app
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── java
│ │ └── com
│ │ │ └── easydb
│ │ │ ├── demo
│ │ │ ├── model
│ │ │ │ ├── BaseModel.java
│ │ │ │ └── SimpleData.java
│ │ │ └── MainActivity.java
│ │ │ ├── core
│ │ │ ├── BaseApplication.java
│ │ │ └── BaseActivity.java
│ │ │ └── util
│ │ │ └── LogUtil.java
│ │ └── AndroidManifest.xml
└── build.gradle
├── .idea
├── markdown-navigator
│ └── profiles_settings.xml
└── markdown-navigator.xml
├── gradle.properties
└── README.md
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':easydb'
2 |
--------------------------------------------------------------------------------
/pic/1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrZhousf/EasyDB/HEAD/pic/1.jpg
--------------------------------------------------------------------------------
/easydb/AndroidPlugins.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrZhousf/EasyDB/HEAD/easydb/AndroidPlugins.jar
--------------------------------------------------------------------------------
/easydb/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | easydb
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrZhousf/EasyDB/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrZhousf/EasyDB/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrZhousf/EasyDB/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrZhousf/EasyDB/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MrZhousf/EasyDB/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.idea/markdown-navigator/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/easydb/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | EasyDB
3 | 提示
4 | 当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。
5 | 设置
6 | 取消
7 |
8 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/callback/EasyRunAbs.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.callback;
2 |
3 | /**
4 | * 任务回调接口基类
5 | * @author : zhousf
6 | */
7 |
8 | public abstract class EasyRunAbs {
9 |
10 | public abstract T run() throws Exception;
11 |
12 | public abstract void onMainThread(T data) throws Exception;
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/java/com/easydb/demo/model/BaseModel.java:
--------------------------------------------------------------------------------
1 | package com.easydb.demo.model;
2 |
3 | import com.j256.ormlite.field.DatabaseField;
4 |
5 | /**
6 | * @Description:
7 | * @Functions:
8 | * @Author:
9 | * @Date: 2016-12-28
10 | */
11 | public class BaseModel {
12 |
13 | @DatabaseField
14 | public String father;
15 |
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/annotation/TableModel.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.annotation;
2 |
3 |
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 |
7 | /**
8 | * 表模型注解(自动扫描所有注解的表模型)
9 | * @author : zhousf
10 | */
11 | @Retention(RetentionPolicy.RUNTIME)
12 | public @interface TableModel {
13 |
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/callback/IUpgrade.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.callback;
2 |
3 | import com.easydblib.helper.DBHelper;
4 |
5 | import java.sql.SQLException;
6 |
7 | /**
8 | * 数据库升级接口
9 | * @author : zhousf
10 | */
11 | public interface IUpgrade {
12 |
13 | void upgrade(DBHelper dbHelper, int oldVersion, int newVersion) throws SQLException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/callback/EasyRun.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.callback;
2 |
3 | /**
4 | * 异步任务回调接口
5 | * @author : zhousf
6 | */
7 |
8 | public class EasyRun extends EasyRunAbs{
9 |
10 |
11 | /**
12 | * 异步线程执行
13 | */
14 | @Override
15 | public T run() throws Exception {
16 | return null;
17 | }
18 |
19 | /**
20 | * UI线程执行
21 | * @param data run方法返回参数
22 | */
23 | @Override
24 | public void onMainThread(T data) throws Exception {
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/handler/MessageInfo.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.handler;
2 |
3 | import android.os.Message;
4 |
5 | import com.easydblib.callback.EasyRun;
6 |
7 | /**
8 | * Handler 信息体
9 | * @author : zhousf
10 | */
11 |
12 | public class MessageInfo {
13 |
14 | public int what;
15 |
16 | public EasyRun easyRun;
17 |
18 | public T model;
19 |
20 | public MessageInfo() {
21 | }
22 |
23 | public Message build(){
24 | Message msg = new Message();
25 | msg.what = this.what;
26 | msg.obj = this;
27 | return msg;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/info/OrderInfo.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.info;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * 排序条件
8 | * @author : zhousf
9 | */
10 | public class OrderInfo {
11 |
12 | /**
13 | * 排序集合
14 | * false降序 true升序
15 | */
16 | public Map orders = new HashMap<>();
17 |
18 |
19 | private OrderInfo() {
20 | }
21 |
22 |
23 | public static OrderInfo get(){
24 | return new OrderInfo();
25 | }
26 |
27 | /**
28 | * 排序:false降序 true升序
29 | */
30 | public OrderInfo order(String name, boolean value){
31 | orders.put(name,value);
32 | return this;
33 | }
34 |
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion rootProject.sdkVersion
5 | buildToolsVersion rootProject.buildTools
6 | defaultConfig {
7 | applicationId "com.easydb"
8 | targetSdkVersion rootProject.sdkVersion
9 | minSdkVersion rootProject.minSdkVersion
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | lintOptions {
20 | abortOnError false
21 | }
22 | }
23 |
24 | dependencies {
25 | compile project(':easydb')
26 | compile fileTree(dir: 'libs', include: ['*.jar'])
27 | compile 'com.android.support:appcompat-v7:23.+'
28 | //注解
29 | compile 'com.jakewharton:butterknife:7.0.1'
30 | }
31 |
--------------------------------------------------------------------------------
/easydb/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion rootProject.sdkVersion
5 | buildToolsVersion rootProject.buildTools
6 | resourcePrefix "easydb_"
7 |
8 | defaultConfig {
9 | targetSdkVersion rootProject.sdkVersion
10 | minSdkVersion rootProject.minSdkVersion
11 | versionCode 1
12 | versionName "1.7.9"
13 |
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | tasks.withType(Javadoc) {
24 | options.addStringOption('Xdoclint:none', '-quiet')
25 | options.addStringOption('encoding', 'UTF-8')
26 | options.addStringOption('charSet', 'UTF-8')
27 | }
28 |
29 |
30 | dependencies {
31 | compile fileTree(dir: 'libs', include: ['*.jar'])
32 | compile 'com.j256.ormlite:ormlite-android:5.0'
33 | }
34 |
35 | //apply from: "bintrayUpload.gradle"
36 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/util/CheckUtil.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.util;
2 |
3 | import android.os.Environment;
4 | import android.text.TextUtils;
5 | import android.util.Log;
6 |
7 | import com.easydblib.EasyDBConfig;
8 |
9 | /**
10 | * 检测工具类
11 | * @author : zhousf
12 | */
13 | public class CheckUtil {
14 |
15 | /**
16 | * 判断SD卡是否存在
17 | */
18 | public static boolean checkSD(String databasePath, String databaseName){
19 | boolean sdExist = Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
20 | doLog("SD卡"+(sdExist?"存在":"不存在"));
21 | boolean path = TextUtils.isEmpty(databasePath);
22 | if(path){
23 | doLog("系统数据库");
24 | }else{
25 | doLog("SD卡数据库:"+databasePath+"/"+databaseName);
26 | }
27 | return sdExist && !path;
28 | }
29 |
30 |
31 | /**
32 | * 打印日志
33 | */
34 | private static void doLog(String msg){
35 | if(EasyDBConfig.showDBLog)
36 | Log.d(EasyDBConfig.logTAG,msg);
37 | }
38 |
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/EasyDBConfig.java:
--------------------------------------------------------------------------------
1 | package com.easydblib;
2 |
3 | /**
4 | * EasyDB配置
5 | * @author : zhousf
6 | */
7 |
8 | public class EasyDBConfig {
9 |
10 | public static boolean showDBLog = true;
11 | public static String logTAG = "EasyDB";
12 |
13 | public static Builder init() {
14 | return new Builder();
15 | }
16 |
17 | public EasyDBConfig(Builder builder) {
18 | showDBLog = builder.showDBLog;
19 | logTAG = builder.logTAG;
20 | }
21 |
22 | public static final class Builder{
23 |
24 | private boolean showDBLog;//是否显示数据库操作日志
25 | private String logTAG;//日志显示标识
26 |
27 | public Builder() {
28 |
29 | }
30 |
31 | public EasyDBConfig build(){
32 | return new EasyDBConfig(this);
33 | }
34 |
35 | /**
36 | * 是否显示数据库操作日志
37 | * @param showDBLog true显示 false不显示
38 | */
39 | public Builder showDBLog(boolean showDBLog){
40 | this.showDBLog = showDBLog;
41 | return this;
42 | }
43 |
44 | /**
45 | * 日志显示标识
46 | * @param logTAG 日志标识
47 | */
48 | public Builder setLogTAG(String logTAG){
49 | this.logTAG = logTAG;
50 | return this;
51 | }
52 |
53 | }
54 |
55 |
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/handler/HandlerHelper.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.handler;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 |
7 | import com.easydblib.callback.EasyRun;
8 |
9 | /**
10 | * Handler辅助类:用于线程切换
11 | * @author : zhousf
12 | */
13 |
14 | public class HandlerHelper extends Handler {
15 |
16 | public static final int WHAT_CALLBACK = 1;
17 |
18 | private static HandlerHelper helper;
19 |
20 | public static HandlerHelper get(){
21 | if(helper == null){
22 | synchronized (HandlerHelper.class){
23 | if(helper == null)
24 | helper = new HandlerHelper();
25 | }
26 | }
27 | return helper;
28 | }
29 |
30 |
31 | private HandlerHelper() {
32 | super(Looper.getMainLooper());
33 | }
34 |
35 |
36 | @Override
37 | public void handleMessage(Message msg) {
38 | switch (msg.what){
39 | case WHAT_CALLBACK:
40 | MessageInfo model_msg = (MessageInfo)msg.obj;
41 | EasyRun run_model = model_msg.easyRun;
42 | try {
43 | if(null != run_model)
44 | run_model.onMainThread(model_msg.model);
45 | } catch (Exception e){
46 | e.printStackTrace();
47 | }
48 | break;
49 | }
50 | }
51 |
52 |
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/java/com/easydb/core/BaseApplication.java:
--------------------------------------------------------------------------------
1 | package com.easydb.core;
2 |
3 | import android.app.Application;
4 | import android.os.Environment;
5 | import android.util.Log;
6 |
7 | import com.easydb.demo.model.SimpleData;
8 | import com.easydblib.callback.IUpgrade;
9 | import com.easydblib.helper.DBHelper;
10 |
11 | import java.sql.SQLException;
12 |
13 | /**
14 | * @author : zhousf
15 | */
16 |
17 | public class BaseApplication extends Application {
18 |
19 | static BaseApplication baseApplication;
20 |
21 | public static BaseApplication getApplication() {
22 | return baseApplication;
23 | }
24 |
25 | @Override
26 | public void onCreate() {
27 | super.onCreate();
28 | baseApplication = this;
29 | DBHelper.builder()
30 | .setDbPath(Environment.getExternalStorageDirectory() + "/easy_db")//数据库保存路径
31 | .setDbName("easy")//数据库名称
32 | .setDbVersion(2)//数据库版本号
33 | .showDBLog(true)//显示数据库操作日志
34 | .setLogTAG("EASY_DB")//日志显示标识
35 | .build(this);
36 | DBHelper.builder().onUpgrade(new IUpgrade() {
37 | @Override
38 | public void upgrade(DBHelper dbHelper, int oldVersion, int newVersion) throws SQLException {
39 | Log.d("upgrade","oldVersion="+oldVersion+",newVersion="+newVersion);
40 | if(oldVersion < 2){
41 | //增加字段ext
42 | dbHelper.addColumn(SimpleData.class,"ext",String.class,"100");
43 | }
44 | }
45 | });
46 | }
47 |
48 | @Override
49 | public void onTerminate() {
50 | super.onTerminate();
51 | }
52 |
53 |
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/app/src/main/java/com/easydb/util/LogUtil.java:
--------------------------------------------------------------------------------
1 | package com.easydb.util;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * 日志打印
7 | * @author zhousf
8 | */
9 | public class LogUtil {
10 |
11 | /** 是否开启debug模式 */
12 | public static boolean isDebug = true;
13 |
14 | public LogUtil() {
15 | }
16 |
17 | /**
18 | * 错误
19 | */
20 | public static void e(Class> clazz, String msg){
21 | if(isDebug){
22 | Log.e(clazz.getSimpleName(), msg);
23 | }
24 | }
25 |
26 | public static void e(String clazzName, String msg){
27 | if(isDebug){
28 | Log.e(clazzName, msg);
29 | }
30 | }
31 |
32 | /**
33 | * 信息
34 | */
35 | public static void i(Class> clazz, String msg){
36 | if(isDebug){
37 | Log.i(clazz.getSimpleName(), msg);
38 | }
39 | }
40 |
41 | public static void i(String clazzName, String msg){
42 | if(isDebug){
43 | Log.i(clazzName, msg);
44 | }
45 | }
46 |
47 | /**
48 | * 警告
49 | */
50 | public static void w(Class> clazz, String msg){
51 | if(isDebug){
52 | Log.w(clazz.getSimpleName(), msg);
53 | }
54 | }
55 |
56 | public static void w(String clazzName, String msg){
57 | if(isDebug){
58 | Log.w(clazzName, msg);
59 | }
60 | }
61 |
62 | /**
63 | * 测试
64 | */
65 | public static void d(Class> clazz, String msg){
66 | if(isDebug){
67 | Log.d(clazz.getSimpleName(), msg);
68 | }
69 | }
70 |
71 | public static void d(String clazzName, String msg){
72 | if(isDebug){
73 | Log.d(clazzName, msg);
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/info/Result.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.info;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * 数据库操作结果
8 | * @author : zhousf
9 | */
10 | public class Result {
11 |
12 | public static final int LIST = 1;
13 | public static final int MODEL = 2;
14 | public static final int LINE = 3;
15 | public static final int COUNT = 4;
16 | public static final int IS_EXIST = 5;
17 |
18 | private int type;
19 | private Exception exception;
20 | private List list = new ArrayList<>();
21 | private T model;
22 | private int line;
23 | private long count;
24 | private boolean isExist;
25 |
26 | public Result(int type) {
27 | this.type = type;
28 | }
29 |
30 | public int getType() {
31 | return type;
32 | }
33 |
34 | public Exception getException() {
35 | return exception;
36 | }
37 |
38 | public void setException(Exception exception) {
39 | this.exception = exception;
40 | }
41 |
42 | public List getList() {
43 | return list;
44 | }
45 |
46 | public void setList(List list) {
47 | this.list = list;
48 | }
49 |
50 | public T getModel() {
51 | return model;
52 | }
53 |
54 | public void setModel(T model) {
55 | this.model = model;
56 | }
57 |
58 | public int getLine() {
59 | return line;
60 | }
61 |
62 | public void setLine(int line) {
63 | this.line = line;
64 | }
65 |
66 | public long getCount() {
67 | return count;
68 | }
69 |
70 | public void setCount(long count) {
71 | this.count = count;
72 | }
73 |
74 | public boolean isExist() {
75 | return isExist;
76 | }
77 |
78 | public void setExist(boolean exist) {
79 | isExist = exist;
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/util/CastUtil.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.util;
2 |
3 | import com.j256.ormlite.field.DatabaseField;
4 |
5 | import java.lang.reflect.Field;
6 | import java.lang.reflect.InvocationTargetException;
7 |
8 | /**
9 | * 转换工具
10 | * @author : zhousf
11 | */
12 | public class CastUtil {
13 |
14 |
15 | /**
16 | * 将from赋值给to
17 | * @param from 赋值的model
18 | * @param to 被赋值的model
19 | * @return to
20 | */
21 | public static T castModel(T from,T to) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchFieldException{
22 | if(to != null && from != null){
23 | Field[] field_obj = from.getClass().getDeclaredFields();
24 | for(Field field : field_obj){
25 | // 获取属性的名字
26 | String name = field.getName();
27 | if(!name.equals("serialVersionUID")){
28 | field.setAccessible(true);
29 | Object value_from = field.get(from);
30 | Object value_to = field.get(to);
31 | DatabaseField type = field.getAnnotation(DatabaseField.class);
32 | //判断是否主键
33 | if(type == null || !type.generatedId()){
34 | //赋值
35 | if(value_from!=null && (value_to == null ||!value_to.toString().trim().equals(value_from.toString().trim()))){
36 | Field field_toObj = to.getClass().getDeclaredField(name);
37 | field_toObj.setAccessible(true);
38 | field_toObj.set(to, value_from);
39 | }
40 | }
41 | }
42 | }
43 | return to;
44 | }
45 | return null;
46 | }
47 |
48 |
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/helper/DatabaseSDContext.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.helper;
2 |
3 | import android.content.Context;
4 | import android.content.ContextWrapper;
5 | import android.database.DatabaseErrorHandler;
6 | import android.database.sqlite.SQLiteDatabase;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 |
11 | /**
12 | * SD卡数据库上下文
13 | * @author : zhousf
14 | */
15 | public class DatabaseSDContext extends ContextWrapper {
16 |
17 | private String dbDir;
18 |
19 | public DatabaseSDContext(Context base, String dbDir) {
20 | super(base);
21 | this.dbDir = dbDir;
22 | }
23 |
24 | @Override
25 | public File getDatabasePath(String name) {
26 | File dirFile = new File(dbDir);
27 | if (!dirFile.exists())
28 | dirFile.mkdirs();
29 | // 标记数据库文件是否创建成功
30 | boolean isFileCreateSuccess = false;
31 | // 数据库路径
32 | String dbPath = dbDir +"/" + name;
33 | File dbFile = new File(dbPath);
34 | // 如果数据库文件不存在则创建该文件
35 | if (!dbFile.exists()) {
36 | try {
37 | // 创建文件
38 | isFileCreateSuccess = dbFile.createNewFile();
39 | } catch (IOException e) {
40 | e.printStackTrace();
41 | }
42 | } else
43 | isFileCreateSuccess = true;
44 | //返回数据库文件对象
45 | if (isFileCreateSuccess)
46 | return dbFile;
47 | else
48 | return null;
49 | }
50 |
51 | @Override
52 | public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
53 | return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
54 | }
55 |
56 |
57 | @Override
58 | public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
59 | return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
60 | }
61 |
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/app/src/main/java/com/easydb/demo/model/SimpleData.java:
--------------------------------------------------------------------------------
1 | package com.easydb.demo.model;
2 |
3 | import com.easydblib.annotation.TableModel;
4 | import com.j256.ormlite.field.DatabaseField;
5 |
6 | import java.text.SimpleDateFormat;
7 | import java.util.Date;
8 |
9 | /**
10 | * A simple demonstration object we are creating and persisting to the database.
11 | */
12 | @TableModel
13 | public class SimpleData {
14 |
15 | //以下字段别名可以通过AndroidStudio插件生成
16 | public final static String _id = "id";
17 | public final static String _index = "index";
18 | public final static String _description = "description";
19 | public final static String _myDouble = "myDouble";
20 | public final static String _myFloat = "myFloat";
21 | public final static String _myLong = "myLong";
22 | public final static String _date = "date";
23 | public final static String _group1 = "group1";
24 | public final static String _group2 = "group2";
25 | public final static String _ext = "ext";
26 |
27 | @DatabaseField(generatedId = true)
28 | public int id;
29 | @DatabaseField(index = true)
30 | public int index;
31 | @DatabaseField
32 | public String description;
33 | @DatabaseField
34 | public double myDouble;
35 | @DatabaseField
36 | public float myFloat;
37 | @DatabaseField
38 | public long myLong;
39 | @DatabaseField
40 | public Date date;
41 | @DatabaseField
42 | public boolean group1;
43 | @DatabaseField
44 | public boolean group2;
45 | @DatabaseField
46 | public String ext;
47 |
48 |
49 | //必须有无参构造方法
50 | public SimpleData() {
51 | }
52 |
53 | public SimpleData(int index,String description) {
54 | this.date = new Date(System.currentTimeMillis());
55 | this.index = index;
56 | this.description = description;
57 | this.group1 = ((index % 2) == 0);
58 | this.group2 = ((index % 4) == 0);
59 | this.myDouble = 5.0;
60 | this.myFloat = 2;
61 | this.myLong = 6;
62 | }
63 |
64 | @Override
65 | public String toString() {
66 | StringBuilder sb = new StringBuilder();
67 | sb.append("id=").append(id);
68 | sb.append(", ").append("index=").append(index);
69 | sb.append(", ").append("description=").append(description);
70 | SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.S");
71 | sb.append(", ").append("date=").append(dateFormatter.format(date));
72 | sb.append(", ").append("group1=").append(group1);
73 | sb.append(", ").append("group2=").append(group2);
74 | sb.append(", ").append("ext=").append(ext);
75 | return sb.toString();
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/info/Where.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.info;
2 |
3 | /**
4 | * Where信息体
5 | * @author : zhousf
6 | */
7 | public class Where {
8 |
9 | public final static String EQ = "equal";//等于
10 | public final static String LIKE = "like";//模糊匹配
11 | public final static String BETWEEN = "between";//指定范围
12 | public final static String OR = "or";//或者
13 | public final static String AND = "and";//并且
14 | public final static String LT = "lt";//小于
15 | public final static String GT = "gt";//大于
16 | public final static String GE = "ge";//大于等于
17 | public final static String LE = "le";//小于等于
18 | public final static String NE = "ne";//不等于
19 | public final static String IN = "in";//包含
20 | public final static String NOT_IN = "notIn";//不包含
21 | public final static String INIT = "init";//初始化
22 | public final static String UPDATE = "update";//更新
23 |
24 |
25 | public String andOr = AND;//连接符
26 | public String op = INIT;//操作符
27 | public String name;//操作名
28 | public Object value;//操作数
29 |
30 | public Object low;
31 | public Object high;
32 |
33 | public Object[] values;
34 |
35 |
36 | public static Where get(String andOr){
37 | return new Where(andOr);
38 | }
39 |
40 | public static Where get(String andOr, String op, String name, Object value){
41 | return new Where(andOr,op,name,value);
42 | }
43 |
44 | public static Where get(String andOr, String op, String name, Object[] values){
45 | return new Where(andOr,op,name,values);
46 | }
47 |
48 | public static Where get(String andOr, String op, String name, Object low, Object high){
49 | return new Where(andOr,op, name, low, high);
50 | }
51 |
52 | private Where(String andOr) {
53 | this.andOr = andOr;
54 | }
55 |
56 | private Where(String andOr, String op, String name, Object value) {
57 | this.andOr = andOr;
58 | this.op = op;
59 | this.name = name;
60 | this.value = value;
61 | }
62 |
63 | private Where(String andOr, String op, String name, Object low, Object high) {
64 | this.andOr = andOr;
65 | this.op = op;
66 | this.name = name;
67 | this.low = low;
68 | this.high = high;
69 | }
70 |
71 | private Where(String andOr, String op, String name, Object[] values) {
72 | this.andOr = andOr;
73 | this.op = op;
74 | this.name = name;
75 | this.values = values;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/helper/DBHelper.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.helper;
2 |
3 | import android.content.Context;
4 |
5 | import com.easydblib.callback.IUpgrade;
6 |
7 | import java.sql.SQLException;
8 | import java.util.Date;
9 | import java.util.List;
10 |
11 | /**
12 | * 数据库操作单例
13 | * @author : zhousf
14 | */
15 | public class DBHelper extends BaseDBHelper{
16 |
17 |
18 | private static DBHelper singleton;
19 |
20 | private static DBBuilder dbBuilder;
21 |
22 | public static DBHelper init(Context context,DBBuilder dbBuilder) {
23 | if (null == singleton) {
24 | synchronized (DBHelper.class) {
25 | if (null == singleton) {
26 | singleton = new DBHelper(context,dbBuilder);
27 | }
28 | }
29 | }
30 | return singleton;
31 | }
32 |
33 | public static DBHelper get(){
34 | return singleton;
35 | }
36 |
37 | private DBHelper(Context context,DBBuilder dbBuilder) {
38 | super(context, dbBuilder.getDbPath(),dbBuilder.getDbName(),dbBuilder.getDbVersion(),dbBuilder.getTables());
39 | }
40 |
41 | public static DBBuilder builder(){
42 | if(dbBuilder == null){
43 | dbBuilder = new DBBuilder();
44 | }
45 | return dbBuilder;
46 | }
47 |
48 |
49 | @Override
50 | protected boolean upgrade(int oldVersion, int newVersion) throws SQLException {
51 | if(dbBuilder != null){
52 | List upgrades = dbBuilder.getUpgrades();
53 | if(upgrades != null && !upgrades.isEmpty()){
54 | for(IUpgrade upgrade : upgrades){
55 | upgrade.upgrade(this,oldVersion,newVersion);
56 | }
57 | return true;
58 | }
59 | }
60 | return false;
61 | }
62 |
63 | /**
64 | * 增加字段
65 | * @param table 表
66 | * @param columnName 增加列名
67 | * @param columnType 列类型
68 | * @param defaultValue 默认值
69 | */
70 | public void addColumn(Class table,String columnName,Object columnType,Object defaultValue){
71 | try {
72 | String column;
73 | String value = String.valueOf(defaultValue);;
74 | if(columnType == String.class || columnType == Date.class){
75 | column = "TEXT";
76 | value = "'"+String.valueOf(defaultValue)+"'";
77 | } else if(columnType == Long.class || columnType == Integer.class){
78 | column = "INTEGER";
79 | } else if(columnType == Boolean.class){
80 | column = "NUMERIC";
81 | } else if(columnType == Double.class || columnType == Float.class){
82 | column = "REAL";
83 | }else{
84 | column = "TEXT";
85 | value = "'"+String.valueOf(defaultValue)+"'";
86 | }
87 | final String sql = "ALTER TABLE '"+table.getSimpleName().toLowerCase()
88 | +"' ADD COLUMN "+columnName+" "+column+" DEFAULT "+value+";";
89 | getDao(table).executeRaw(sql);
90 | } catch (SQLException e) {
91 | e.printStackTrace();
92 | }
93 | }
94 |
95 |
96 |
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/easydb/bintrayUpload.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.github.dcendents.android-maven'
2 | apply plugin: 'com.jfrog.bintray'
3 |
4 | // load properties
5 | Properties properties = new Properties()
6 | File localPropertiesFile = project.file("local.properties");
7 | if(localPropertiesFile.exists()){
8 | properties.load(localPropertiesFile.newDataInputStream())
9 | }
10 | File projectPropertiesFile = project.file("project.properties");
11 | if(projectPropertiesFile.exists()){
12 | properties.load(projectPropertiesFile.newDataInputStream())
13 | }
14 |
15 | // read properties
16 | def projectName = properties.getProperty("project.name")
17 | def projectGroupId = properties.getProperty("project.groupId")
18 | def projectArtifactId = properties.getProperty("project.artifactId")
19 | def projectVersionName = android.defaultConfig.versionName
20 | def projectPackaging = properties.getProperty("project.packaging")
21 | def projectSiteUrl = properties.getProperty("project.siteUrl")
22 | def projectGitUrl = properties.getProperty("project.gitUrl")
23 |
24 | def developerId = properties.getProperty("developer.id")
25 | def developerName = properties.getProperty("developer.name")
26 | def developerEmail = properties.getProperty("developer.email")
27 |
28 | def bintrayUser = properties.getProperty("bintray.user")
29 | def bintrayApikey = properties.getProperty("bintray.apikey")
30 |
31 | def javadocName = properties.getProperty("javadoc.name")
32 |
33 | group = projectGroupId
34 |
35 | // This generates POM.xml with proper parameters
36 | install {
37 | repositories.mavenInstaller {
38 | pom {
39 | project {
40 | name projectName
41 | groupId projectGroupId
42 | artifactId projectArtifactId
43 | version projectVersionName
44 | packaging projectPackaging
45 | url projectSiteUrl
46 | licenses {
47 | license {
48 | name 'The Apache Software License, Version 2.0'
49 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
50 | }
51 | }
52 | developers {
53 | developer {
54 | id developerId
55 | name developerName
56 | email developerEmail
57 | }
58 | }
59 | scm {
60 | connection projectGitUrl
61 | developerConnection projectGitUrl
62 | url projectSiteUrl
63 | }
64 | }
65 | }
66 | }
67 | }
68 |
69 | // This generates sources.jar
70 | task sourcesJar(type: Jar) {
71 | from android.sourceSets.main.java.srcDirs
72 | classifier = 'sources'
73 | }
74 |
75 | task javadoc(type: Javadoc) {
76 | source = android.sourceSets.main.java.srcDirs
77 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
78 | }
79 |
80 | // This generates javadoc.jar
81 | task javadocJar(type: Jar, dependsOn: javadoc) {
82 | classifier = 'javadoc'
83 | from javadoc.destinationDir
84 | }
85 |
86 | artifacts {
87 | archives javadocJar
88 | archives sourcesJar
89 | }
90 |
91 | // javadoc configuration
92 | javadoc {
93 | options{
94 | encoding "UTF-8"
95 | charSet 'UTF-8'
96 | author true
97 | version projectVersionName
98 | links "http://docs.oracle.com/javase/7/docs/api"
99 | title javadocName
100 | }
101 | }
102 |
103 | // bintray configuration
104 | bintray {
105 | user = bintrayUser
106 | key = bintrayApikey
107 | configurations = ['archives']
108 | pkg {
109 | repo = "maven"
110 | name = projectName
111 | websiteUrl = projectSiteUrl
112 | vcsUrl = projectGitUrl
113 | licenses = ["Apache-2.0"]
114 | publish = true
115 | }
116 | }
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/dao/DBDao.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.dao;
2 |
3 |
4 | import com.easydblib.callback.EasyRun;
5 | import com.easydblib.info.OrderInfo;
6 | import com.easydblib.info.WhereInfo;
7 | import com.j256.ormlite.dao.Dao;
8 | import com.j256.ormlite.stmt.QueryBuilder;
9 |
10 | import java.util.List;
11 | import java.util.concurrent.Callable;
12 |
13 |
14 | /**
15 | * 数据库操作接口
16 | * @author : zhousf
17 | */
18 | public interface DBDao {
19 |
20 | /**
21 | * 增加
22 | * @param model 映射类
23 | * @return 影响行数
24 | */
25 | int add(T model);
26 |
27 | /**
28 | * 增加集合
29 | * @param list 映射类集合
30 | * @return 影响行数
31 | */
32 | int add(List list);
33 |
34 | /**
35 | * 增加或更新
36 | * @param model 映射类
37 | * @return 影响行数
38 | */
39 | int addOrUpdate(T model);
40 |
41 | /**
42 | * 不存在时增加
43 | * @param model 映射类
44 | * @return 增加的对象
45 | */
46 | T addIfNotExists(T model);
47 |
48 | /**
49 | * 删除
50 | * @param model 映射类
51 | * @return 影响行数
52 | */
53 | int delete(T model);
54 |
55 | /**
56 | * 删除集合
57 | * @param list 映射类集合
58 | * @return 影响行数
59 | */
60 | int delete(List list);
61 |
62 | /**
63 | * 根据条件删除
64 | * @param whereInfo 查询信息体
65 | * @return 影响行数
66 | */
67 | int delete(WhereInfo whereInfo);
68 |
69 | /**
70 | * 更新
71 | * @param model 映射类
72 | * @return 影响行数
73 | */
74 | int update(T model);
75 |
76 | /**
77 | * 更新
78 | * @param whereInfo 更新条件
79 | */
80 | int update(WhereInfo whereInfo);
81 |
82 | /**
83 | * 查询所有
84 | * @return 映射类集合
85 | */
86 | List queryAll();
87 |
88 | /**
89 | * 查询所有并排序
90 | * @param orderInfo 排序信息体
91 | * @return 映射类集合
92 | */
93 | List queryAll(OrderInfo orderInfo);
94 |
95 | /**
96 | * 多条件查询并排序
97 | * @param whereInfo 查询信息体
98 | * @return 映射类集合
99 | */
100 | List query(WhereInfo whereInfo);
101 |
102 |
103 | /**
104 | * 分页查询
105 | * @param whereInfo 查询信息体
106 | * @return 映射类集合
107 | */
108 | List queryLimit(WhereInfo whereInfo);
109 |
110 | /**
111 | * 自定义查询
112 | * @param queryBuilder 查询构建
113 | * @return 映射类集合
114 | */
115 | List query(QueryBuilder queryBuilder);
116 |
117 | /**
118 | * 统计条目数
119 | * @return 条目数
120 | */
121 | long countOf();
122 |
123 | /**
124 | * 统计条目数
125 | * @param whereInfo 查询信息体
126 | * @return 条目数
127 | */
128 | long countOf(WhereInfo whereInfo);
129 |
130 | /**
131 | * 是否存在
132 | * @param whereInfo 查询信息体
133 | * @return true 存在 false 不存在
134 | */
135 | boolean isExist(WhereInfo whereInfo);
136 |
137 | /**
138 | * 执行原生的SQL语句
139 | * @param statement SQL语句
140 | * @param arguments 参数值-占位符?的值
141 | * @return 影响行数
142 | */
143 | int executeRaw(String statement, String... arguments);
144 |
145 | /**
146 | * 清空表
147 | * @return 条目数
148 | */
149 | int clearTable();
150 |
151 | /**
152 | * 删除表
153 | * @return 条目数
154 | */
155 | int dropTable();
156 |
157 | /**
158 | * 获取数据表DAO
159 | * @return dao
160 | */
161 | Dao fetchDao();
162 |
163 | /**
164 | * 获取表名
165 | * @return 表名
166 | */
167 | String getTableName();
168 |
169 | /**
170 | * 执行事务
171 | * @param callable 事务回调
172 | */
173 | void callInTransaction(Callable callable);
174 |
175 | /**
176 | * 批处理-大量数据库操作时请采用该方法(性能最优)
177 | * @param callable 回调
178 | */
179 | CT callBatchTasks(Callable callable);
180 |
181 | /**
182 | * 异步执行
183 | * @param easyRun 异步run
184 | */
185 | void asyncTask(EasyRun easyRun);
186 |
187 | }
188 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/info/WhereInfo.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.info;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | /**
9 | * 数据库操作条件
10 | * @author : zhousf
11 | */
12 | public class WhereInfo {
13 |
14 | /**
15 | * 条件集合:
16 | */
17 | public List wheres = new ArrayList<>();
18 |
19 | /**
20 | * 排序集合
21 | * false降序 true升序
22 | */
23 | public Map orders = new HashMap<>();
24 |
25 | //每页条目数
26 | public int limit;
27 | //返回条目数
28 | public int size;
29 | //当前页
30 | public int currentPage = 0;
31 |
32 | private boolean isOr = false;
33 |
34 | private WhereInfo() {
35 | }
36 |
37 | public static WhereInfo get(){
38 | return new WhereInfo();
39 | }
40 |
41 | /**
42 | * equal条件:等于
43 | */
44 | public WhereInfo equal(String name, Object value){
45 | wheres.add(Where.get(andOr(),Where.EQ,name,value));
46 | return this;
47 | }
48 |
49 | /**
50 | * like条件:注意使用%(例如:value="北京%",value="%北京",value="%北京%")
51 | */
52 | public WhereInfo like(String name, Object value){
53 | wheres.add(Where.get(andOr(),Where.LIKE,name,value));
54 | return this;
55 | }
56 |
57 | /**
58 | * between条件
59 | */
60 | public WhereInfo between(String name,Object low, Object high){
61 | wheres.add(Where.get(andOr(),Where.BETWEEN,name,low,high));
62 | return this;
63 | }
64 |
65 | /**
66 | * or条件
67 | */
68 | public WhereInfo or(){
69 | isOr = true;
70 | return this;
71 | }
72 |
73 | /**
74 | * 更新
75 | */
76 | public WhereInfo update(String name, Object value){
77 | wheres.add(Where.get(andOr(),Where.UPDATE,name,value));
78 | return this;
79 | }
80 |
81 | /**
82 | * 排序:false降序 true升序
83 | */
84 | public WhereInfo order(String name, boolean value){
85 | orders.put(name,value);
86 | return this;
87 | }
88 |
89 | /**
90 | * 分页:每页条目数
91 | */
92 | public WhereInfo limit(int limit) {
93 | this.limit = limit;
94 | return this;
95 | }
96 |
97 | /**
98 | * 小于
99 | */
100 | public WhereInfo lt(String name, Object value){
101 | wheres.add(Where.get(andOr(),Where.LT,name,value));
102 | return this;
103 | }
104 |
105 | /**
106 | * 大于
107 | */
108 | public WhereInfo gt(String name, Object value){
109 | wheres.add(Where.get(andOr(),Where.GT,name,value));
110 | return this;
111 | }
112 |
113 | /**
114 | * 大于等于
115 | */
116 | public WhereInfo ge(String name, Object value){
117 | wheres.add(Where.get(andOr(),Where.GE,name,value));
118 | return this;
119 | }
120 |
121 | /**
122 | * 小于等于
123 | */
124 | public WhereInfo le(String name, Object value){
125 | wheres.add(Where.get(andOr(),Where.LE,name,value));
126 | return this;
127 | }
128 |
129 | /**
130 | * 不等于
131 | */
132 | public WhereInfo ne(String name, Object value){
133 | wheres.add(Where.get(andOr(),Where.NE,name,value));
134 | return this;
135 | }
136 |
137 | /**
138 | * 包含
139 | */
140 | public WhereInfo in(String name, Object... value){
141 | wheres.add(Where.get(andOr(),Where.IN,name,value));
142 | return this;
143 | }
144 |
145 | /**
146 | * 不包含
147 | */
148 | public WhereInfo notIn(String name, Object... value){
149 | wheres.add(Where.get(andOr(),Where.NOT_IN,name,value));
150 | return this;
151 | }
152 |
153 |
154 | private String andOr(){
155 | if(isOr){
156 | isOr = false;
157 | return Where.OR;
158 | }else{
159 | return Where.AND;
160 | }
161 | }
162 |
163 |
164 | }
165 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/helper/BaseDBHelper.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.helper;
2 |
3 | import android.content.Context;
4 | import android.database.sqlite.SQLiteDatabase;
5 | import android.util.Log;
6 |
7 | import com.easydblib.dao.DBDao;
8 | import com.easydblib.dao.BaseDaoImp;
9 | import com.easydblib.util.CheckUtil;
10 | import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
11 | import com.j256.ormlite.dao.Dao;
12 | import com.j256.ormlite.support.ConnectionSource;
13 | import com.j256.ormlite.table.TableUtils;
14 |
15 | import java.sql.SQLException;
16 | import java.util.ArrayList;
17 | import java.util.List;
18 | import java.util.Map;
19 | import java.util.concurrent.ConcurrentHashMap;
20 |
21 | /**
22 | * 数据库辅助基类
23 | * @author : zhousf
24 | * 引入版本:com.j256.ormlite:ormlite-android:5.0
25 | */
26 | public abstract class BaseDBHelper extends OrmLiteSqliteOpenHelper {
27 |
28 | private List> modelClasses = new ArrayList<>();
29 |
30 | private Map daoMap = new ConcurrentHashMap<>();
31 |
32 | private Map helperMap = new ConcurrentHashMap<>();
33 |
34 | /**
35 | * 自定义数据库升级:true自定义,false默认升级(删除所有表并重新创建)
36 | */
37 | protected abstract boolean upgrade(int oldVersion, int newVersion) throws SQLException;
38 |
39 |
40 | /**
41 | * 数据库构造方法
42 | * @param context 上下文
43 | * @param databasePath 数据库路径:若为空则系统保存数据库
44 | * @param databaseName 数据库名称
45 | * @param databaseVersion 数据库版本
46 | * @param modelClasses 表
47 | */
48 | public BaseDBHelper(Context context, String databasePath, String databaseName,
49 | int databaseVersion,
50 | List> modelClasses) {
51 | //若SD卡不存在则为系统数据库
52 | super(CheckUtil.checkSD(databasePath,databaseName) ? new DatabaseSDContext(context.getApplicationContext(),databasePath) : context.getApplicationContext(),
53 | databaseName, null, databaseVersion);
54 | for(Class> table : modelClasses){
55 | if(!this.modelClasses.contains(table)){
56 | this.modelClasses.add(table);
57 | }
58 | }
59 | }
60 |
61 | @Override
62 | public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
63 | try {
64 | for (Class> clazz: modelClasses) {
65 | TableUtils.createTable(connectionSource, clazz);
66 | }
67 | } catch (SQLException e) {
68 | Log.e("BaseDBHelper", "Can't create database", e);
69 | throw new RuntimeException(e);
70 | }
71 | }
72 |
73 | @Override
74 | public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
75 | try {
76 | if(!upgrade(oldVersion,newVersion)){
77 | //默认升级(删除所有表并重新创建)
78 | for (Class> clazz: modelClasses) {
79 | TableUtils.dropTable(connectionSource, clazz, true);
80 | }
81 | // after we drop the old databases, we create the new ones
82 | onCreate(database, connectionSource);
83 | }
84 | } catch (SQLException e) {
85 | Log.e("BaseDBHelper", "Can't drop databases", e);
86 | throw new RuntimeException(e);
87 | }
88 | }
89 |
90 | @SuppressWarnings(value = "unchecked")
91 | public Dao fetchDao(Class clazz) {
92 | Dao dao = null;
93 | try {
94 | String className = clazz.getSimpleName();
95 | if (!daoMap.containsKey(className)) {
96 | dao = super.getDao(clazz);
97 | if(null != dao)
98 | daoMap.put(className, dao);
99 | }
100 | dao = daoMap.get(className);
101 | }catch (SQLException e){
102 | e.printStackTrace();
103 | }
104 | return dao;
105 | }
106 |
107 | @SuppressWarnings(value = "unchecked")
108 | public DBDao dao(Class clazz){
109 | String className = clazz.getSimpleName();
110 | if(!helperMap.containsKey(className)){
111 | helperMap.put(className,new BaseDaoImp<>(this,clazz));
112 | }
113 | return helperMap.get(className);
114 | }
115 |
116 | @Override
117 | public void close() {
118 | super.close();
119 | daoMap.clear();
120 | helperMap.clear();
121 | }
122 |
123 |
124 |
125 |
126 | }
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/dao/RealBaseDao.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.dao;
2 |
3 |
4 | import com.easydblib.callback.EasyRun;
5 | import com.easydblib.info.OrderInfo;
6 | import com.easydblib.info.Result;
7 | import com.easydblib.info.WhereInfo;
8 | import com.j256.ormlite.dao.Dao;
9 | import com.j256.ormlite.stmt.QueryBuilder;
10 |
11 | import java.util.List;
12 | import java.util.concurrent.Callable;
13 |
14 |
15 | /**
16 | * 数据库操作接口
17 | * @author : zhousf
18 | */
19 | public interface RealBaseDao {
20 |
21 | /**
22 | * 增加
23 | * @param model 映射类
24 | * @return 影响行数
25 | */
26 | Result add(T model);
27 |
28 | /**
29 | * 增加集合
30 | * @param list 映射类集合
31 | * @return 影响行数
32 | */
33 | Result add(List list);
34 |
35 | /**
36 | * 增加或更新
37 | * @param model 映射类
38 | * @return 影响行数
39 | */
40 | Result addOrUpdate(T model);
41 |
42 | /**
43 | * 不存在时增加
44 | * @param model 映射类
45 | * @return 增加的对象
46 | */
47 | Result addIfNotExists(T model);
48 |
49 | /**
50 | * 删除
51 | * @param model 映射类
52 | * @return 影响行数
53 | */
54 | Result delete(T model);
55 |
56 | /**
57 | * 删除集合
58 | * @param list 映射类集合
59 | * @return 影响行数
60 | */
61 | Result delete(List list);
62 |
63 | /**
64 | * 根据条件删除
65 | * @param whereInfo 查询信息体
66 | * @return 影响行数
67 | */
68 | Result delete(WhereInfo whereInfo);
69 |
70 | /**
71 | * 更新
72 | * @param model 映射类
73 | * @return 影响行数
74 | */
75 | Result update(T model);
76 |
77 | /**
78 | * 更新
79 | * @param whereInfo 更新条件
80 | */
81 | Result update(WhereInfo whereInfo);
82 |
83 | /**
84 | * 查询所有
85 | * @return 映射类集合
86 | */
87 | Result queryAll();
88 |
89 | /**
90 | * 查询所有并排序
91 | * @param orderInfo 排序信息体
92 | * @return 映射类集合
93 | */
94 | Result queryAll(OrderInfo orderInfo);
95 |
96 | /**
97 | * 多条件查询并排序
98 | * @param whereInfo 查询信息体
99 | * @return 映射类集合
100 | */
101 | Result query(WhereInfo whereInfo);
102 |
103 |
104 | /**
105 | * 分页查询
106 | * @param whereInfo 查询信息体
107 | * @return 映射类集合
108 | */
109 | Result queryLimit(WhereInfo whereInfo);
110 |
111 | /**
112 | * 自定义查询
113 | * @param queryBuilder 查询构建
114 | * @return 映射类集合
115 | */
116 | Result query(QueryBuilder queryBuilder);
117 |
118 | /**
119 | * 统计条目数
120 | * @return 条目数
121 | */
122 | Result countOf();
123 |
124 | /**
125 | * 统计条目数
126 | * @param whereInfo 查询信息体
127 | * @return 条目数
128 | */
129 | Result countOf(WhereInfo whereInfo);
130 |
131 | /**
132 | * 是否存在
133 | * @param whereInfo 查询信息体
134 | * @return true 存在 false 不存在
135 | */
136 | Result isExist(WhereInfo whereInfo);
137 |
138 | /**
139 | * 执行原生的SQL语句
140 | * @param statement SQL语句
141 | * @param arguments 参数值-占位符?的值
142 | * @return 影响行数
143 | */
144 | Result executeRaw(String statement, String... arguments);
145 |
146 | /**
147 | * 清空表
148 | * @return 条目数
149 | */
150 | Result clearTable();
151 |
152 | /**
153 | * 删除表
154 | * @return 条目数
155 | */
156 | Result dropTable();
157 |
158 | /**
159 | * 获取数据表DAO
160 | * @return dao
161 | */
162 | Dao fetchDao();
163 |
164 | /**
165 | * 获取表名
166 | * @return 表名
167 | */
168 | String getTableName();
169 |
170 | /**
171 | * 执行事务
172 | * @param callable 事务回调
173 | */
174 | void callInTransaction(Callable callable);
175 |
176 | /**
177 | * 批处理-大量数据库操作时请采用该方法(性能最优)
178 | * @param callable 回调
179 | */
180 | CT callBatchTasks(Callable callable);
181 |
182 | /**
183 | * 异步执行
184 | * @param easyRun 异步run
185 | */
186 | void asyncTask(EasyRun easyRun);
187 |
188 | }
189 |
--------------------------------------------------------------------------------
/.idea/markdown-navigator.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/dao/BaseDaoImp.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.dao;
2 |
3 | import com.easydblib.callback.EasyRun;
4 | import com.easydblib.handler.EasyDBProxyHandler;
5 | import com.easydblib.helper.BaseDBHelper;
6 | import com.easydblib.info.OrderInfo;
7 | import com.easydblib.info.WhereInfo;
8 | import com.j256.ormlite.dao.Dao;
9 | import com.j256.ormlite.stmt.QueryBuilder;
10 |
11 | import java.lang.reflect.ParameterizedType;
12 | import java.lang.reflect.Type;
13 | import java.util.List;
14 | import java.util.concurrent.Callable;
15 |
16 | /**
17 | * 数据库操作接口实现类
18 | * @author : zhousf
19 | */
20 | public class BaseDaoImp implements DBDao {
21 |
22 | private Dao dao;
23 |
24 | private RealBaseDao baseDao;
25 |
26 | public BaseDaoImp(BaseDBHelper helper, Class clazz) {
27 | try {
28 | Class mClass = clazz!=null ? clazz : initClazz();
29 | String databaseName = helper.getDatabaseName();
30 | dao = helper.fetchDao(mClass);
31 | baseDao = new EasyDBProxyHandler(helper,dao,mClass,databaseName).getProxy(new RealBaseDaoImpl<>(dao));
32 | } catch (Exception e){
33 | e.printStackTrace();
34 | }
35 | }
36 |
37 | @SuppressWarnings(value = "all")
38 | private Class initClazz(){
39 | Type genType = getClass().getGenericSuperclass();
40 | Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
41 | if(params[0] instanceof Class){
42 | return (Class) params[0];
43 | }else{
44 | return null;
45 | }
46 | }
47 |
48 | @Override
49 | public int add(T model) {
50 | return baseDao.add(model).getLine();
51 | }
52 |
53 | @Override
54 | public int add(List list) {
55 | return baseDao.add(list).getLine();
56 | }
57 |
58 | @Override
59 | public int addOrUpdate(T model) {
60 | return baseDao.addOrUpdate(model).getLine();
61 | }
62 |
63 | @Override
64 | public T addIfNotExists(T model) {
65 | return baseDao.addIfNotExists(model).getModel();
66 | }
67 |
68 | @Override
69 | public int delete(T model) {
70 | return baseDao.delete(model).getLine();
71 | }
72 |
73 | @Override
74 | public int delete(List list) {
75 | return baseDao.delete(list).getLine();
76 | }
77 |
78 | @Override
79 | public int delete(WhereInfo whereInfo) {
80 | return baseDao.delete(whereInfo).getLine();
81 | }
82 |
83 | @Override
84 | public int update(T model) {
85 | return baseDao.update(model).getLine();
86 | }
87 |
88 | @Override
89 | public int update(WhereInfo whereInfo) {
90 | return baseDao.update(whereInfo).getLine();
91 | }
92 |
93 | @Override
94 | public List queryAll() {
95 | return baseDao.queryAll().getList();
96 | }
97 |
98 | @Override
99 | public List queryAll(OrderInfo orderInfo) {
100 | return baseDao.queryAll(orderInfo).getList();
101 | }
102 |
103 | @Override
104 | public List query(WhereInfo whereInfo) {
105 | return baseDao.query(whereInfo).getList();
106 | }
107 |
108 | @Override
109 | public List queryLimit(WhereInfo whereInfo) {
110 | return baseDao.queryLimit(whereInfo).getList();
111 | }
112 |
113 | @Override
114 | public List query(QueryBuilder queryBuilder){
115 | return baseDao.query(queryBuilder).getList();
116 | }
117 |
118 | @Override
119 | public long countOf() {
120 | return baseDao.countOf(null).getCount();
121 | }
122 |
123 | @Override
124 | public long countOf(WhereInfo whereInfo) {
125 | return baseDao.countOf(whereInfo).getCount();
126 | }
127 |
128 | @Override
129 | public boolean isExist(WhereInfo whereInfo){
130 | return baseDao.isExist(whereInfo).isExist();
131 | }
132 |
133 | @Override
134 | public int executeRaw(String statement, String... arguments) {
135 | return baseDao.executeRaw(statement,arguments).getLine();
136 | }
137 |
138 | @Override
139 | public Dao fetchDao(){
140 | return dao;
141 | }
142 |
143 | @Override
144 | public String getTableName() {
145 | return baseDao.getTableName();
146 | }
147 |
148 | @Override
149 | public int clearTable(){
150 | return baseDao.clearTable().getLine();
151 | }
152 |
153 | @Override
154 | public int dropTable(){
155 | return baseDao.dropTable().getLine();
156 | }
157 |
158 | @Override
159 | public void callInTransaction(Callable callable){
160 | baseDao.callInTransaction(callable);
161 | }
162 |
163 | @Override
164 | public CT callBatchTasks(Callable callable){
165 | return baseDao.callBatchTasks(callable);
166 | }
167 |
168 | @Override
169 | public void asyncTask(final EasyRun easyRun) {
170 | baseDao.asyncTask(easyRun);
171 | }
172 |
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/helper/DBBuilder.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.helper;
2 |
3 |
4 | import android.content.Context;
5 | import android.text.TextUtils;
6 | import android.util.Log;
7 |
8 | import com.easydblib.EasyDBConfig;
9 | import com.easydblib.annotation.TableModel;
10 | import com.easydblib.callback.IUpgrade;
11 |
12 | import java.io.IOException;
13 | import java.util.ArrayList;
14 | import java.util.Enumeration;
15 | import java.util.List;
16 |
17 | import dalvik.system.DexFile;
18 |
19 | /**
20 | * 数据库构建器
21 | * @author : zhousf
22 | */
23 | public class DBBuilder {
24 |
25 | //版本号
26 | private int dbVersion;
27 |
28 | //数据库存放路径
29 | private String dbPath;
30 |
31 | //数据库名称
32 | private String dbName;
33 |
34 | //表
35 | private List> tables;
36 |
37 | private List upgrades;
38 |
39 | //是否显示数据库操作日志
40 | private boolean showDBLog;
41 |
42 | //日志显示标识
43 | private String logTAG;
44 |
45 | public DBBuilder() {
46 | //默认为系统数据库
47 | dbPath = null;
48 | dbName = "easy_database.db";
49 | tables = new ArrayList<>();
50 | }
51 |
52 | /**
53 | * 数据库升级回调
54 | * @param upgrade 升级接口回调
55 | */
56 | public DBBuilder onUpgrade(IUpgrade upgrade){
57 | if(upgrades == null){
58 | upgrades = new ArrayList<>();
59 | }
60 | upgrades.add(upgrade);
61 | return this;
62 | }
63 |
64 | /**
65 | * 设置数据库版本号
66 | * @param dbVersion 版本号
67 | */
68 | public DBBuilder setDbVersion(int dbVersion) {
69 | this.dbVersion = dbVersion;
70 | return this;
71 | }
72 |
73 | /**
74 | * 设置数据库SD卡路径(不设置则为系统数据库)
75 | * @param dbPath 不包含文件名
76 | */
77 | public DBBuilder setDbPath(String dbPath) {
78 | this.dbPath = dbPath;
79 | return this;
80 | }
81 |
82 | /**
83 | * 设置数据库名称
84 | * @param dbName 数据库名称
85 | */
86 | public DBBuilder setDbName(String dbName) {
87 | if(!TextUtils.isEmpty(dbName)){
88 | if(!dbName.endsWith(".db")){
89 | dbName += ".db";
90 | }
91 | this.dbName = dbName;
92 | }
93 | return this;
94 | }
95 |
96 | /**
97 | * 是否显示数据库操作日志
98 | * @param showDBLog true显示 false不显示
99 | */
100 | public DBBuilder showDBLog(boolean showDBLog){
101 | this.showDBLog = showDBLog;
102 | return this;
103 | }
104 |
105 | /**
106 | * 日志显示标识
107 | * @param logTAG 日志标识
108 | */
109 | public DBBuilder setLogTAG(String logTAG){
110 | this.logTAG = logTAG;
111 | return this;
112 | }
113 |
114 | public DBHelper build(Context context){
115 | EasyDBConfig.init()
116 | .showDBLog(showDBLog)
117 | .setLogTAG(logTAG)
118 | .build();
119 | initTable(context,tables);
120 | return DBHelper.init(context,DBBuilder.this);
121 | }
122 |
123 | private void initTable(Context context,List> tables) {
124 | DexFile df = null;
125 | try {
126 | String packageCodePath = context.getPackageCodePath();
127 | df = new DexFile(packageCodePath);
128 | } catch (IOException e) {
129 | e.printStackTrace();
130 | }
131 | if(df == null)
132 | return ;
133 | int num = 0;
134 | StringBuilder log = new StringBuilder();
135 | log.append("----------表清单---------\n");
136 | for (Enumeration enumeration = df.entries(); enumeration.hasMoreElements(); ) {
137 | String className = String.valueOf(enumeration.nextElement());
138 | if(!TextUtils.isEmpty(className) && !className.contains("$")){
139 | Class clazz;
140 | try {
141 | clazz = Class.forName(className,false,context.getClassLoader());
142 | if(clazz != null){
143 | if(clazz.isAnnotationPresent(TableModel.class)){
144 | if(!tables.contains(clazz)){
145 | num ++;
146 | tables.add(clazz);
147 | log.append(num).append(": ").append(className).append("\n");
148 | }
149 |
150 | }
151 | }
152 | } catch (ClassNotFoundException e) {
153 |
154 | } catch (NoClassDefFoundError e){
155 |
156 | } catch (Exception e){
157 |
158 | }
159 | }
160 | }
161 | log.append("-------------------------\n");
162 | Log.d(EasyDBConfig.logTAG,log.toString());
163 | }
164 |
165 | public int getDbVersion() {
166 | return dbVersion;
167 | }
168 |
169 | public String getDbPath() {
170 | return dbPath;
171 | }
172 |
173 | public String getDbName() {
174 | return dbName;
175 | }
176 |
177 | public List> getTables() {
178 | return tables;
179 | }
180 |
181 | public List getUpgrades() {
182 | return upgrades;
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/app/src/main/java/com/easydb/core/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package com.easydb.core;
2 |
3 |
4 | import android.Manifest;
5 | import android.app.AlertDialog;
6 | import android.content.DialogInterface;
7 | import android.content.Intent;
8 | import android.content.pm.PackageManager;
9 | import android.net.Uri;
10 | import android.os.Bundle;
11 | import android.provider.Settings;
12 | import android.support.v4.app.ActivityCompat;
13 | import android.support.v4.content.ContextCompat;
14 | import android.support.v7.app.AppCompatActivity;
15 |
16 | import com.easydb.R;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 | import butterknife.ButterKnife;
22 |
23 | /**
24 | * Activity基类:支持动态权限申请
25 | * @author zhousf
26 | */
27 | public abstract class BaseActivity extends AppCompatActivity implements
28 | ActivityCompat.OnRequestPermissionsResultCallback {
29 |
30 | /**
31 | * 需要进行检测的权限数组
32 | */
33 | protected String[] needPermissions = {
34 | Manifest.permission.ACCESS_COARSE_LOCATION,
35 | Manifest.permission.ACCESS_FINE_LOCATION,
36 | Manifest.permission.WRITE_EXTERNAL_STORAGE,
37 | Manifest.permission.READ_EXTERNAL_STORAGE,
38 | Manifest.permission.READ_PHONE_STATE
39 | };
40 |
41 | private static final int PERMISSION_REQUEST_CODE = 0;
42 |
43 | /**
44 | * 判断是否需要检测,防止不停的弹框
45 | */
46 | private boolean isNeedCheck = true;
47 |
48 | protected abstract int initLayout();
49 |
50 | @Override
51 | protected void onCreate(Bundle savedInstanceState) {
52 | super.onCreate(savedInstanceState);
53 | setContentView(initLayout());
54 | ButterKnife.bind(this);
55 | }
56 |
57 | @Override
58 | protected void onResume() {
59 | super.onResume();
60 | if(isNeedCheck){
61 | checkPermissions(needPermissions);
62 | }
63 | }
64 |
65 | /**
66 | * 检测权限
67 | */
68 | private void checkPermissions(String... permissions) {
69 | List needRequestPermissionList = findDeniedPermissions(permissions);
70 | if (null != needRequestPermissionList && needRequestPermissionList.size() > 0) {
71 | ActivityCompat.requestPermissions(this,
72 | needRequestPermissionList.toArray(new String[needRequestPermissionList.size()]),PERMISSION_REQUEST_CODE);
73 | }
74 | }
75 |
76 | /**
77 | * 获取权限集中需要申请权限的列表
78 | *
79 | */
80 | private List findDeniedPermissions(String[] permissions) {
81 | List needRequestPermissionList = new ArrayList();
82 | for (String perm : permissions) {
83 | if (ContextCompat.checkSelfPermission(this,
84 | perm) != PackageManager.PERMISSION_GRANTED
85 | || ActivityCompat.shouldShowRequestPermissionRationale(
86 | this, perm)) {
87 | needRequestPermissionList.add(perm);
88 | }
89 | }
90 | return needRequestPermissionList;
91 | }
92 |
93 | /**
94 | * 检测是否所有的权限都已经授权
95 | *
96 | */
97 | private boolean verifyPermissions(int[] grantResults) {
98 | for (int result : grantResults) {
99 | if (result != PackageManager.PERMISSION_GRANTED) {
100 | return false;
101 | }
102 | }
103 | return true;
104 | }
105 |
106 | @Override
107 | public void onRequestPermissionsResult(int requestCode,
108 | String[] permissions, int[] paramArrayOfInt) {
109 | if (requestCode == PERMISSION_REQUEST_CODE) {
110 | if (!verifyPermissions(paramArrayOfInt)) {
111 | showMissingPermissionDialog();
112 | isNeedCheck = false;
113 | }
114 | }
115 | }
116 |
117 | /**
118 | * 显示提示信息
119 | */
120 | private void showMissingPermissionDialog() {
121 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
122 | builder.setTitle(R.string.db_notifyTitle);
123 | builder.setMessage(R.string.db_notifyMsg);
124 | // 拒绝, 退出应用
125 | builder.setNegativeButton(R.string.db_cancel,
126 | new DialogInterface.OnClickListener() {
127 | @Override
128 | public void onClick(DialogInterface dialog, int which) {
129 | finish();
130 | }
131 | });
132 |
133 | builder.setPositiveButton(R.string.db_setting,
134 | new DialogInterface.OnClickListener() {
135 | @Override
136 | public void onClick(DialogInterface dialog, int which) {
137 | startAppSettings();
138 | }
139 | });
140 | builder.setCancelable(false);
141 | builder.show();
142 | }
143 |
144 | /**
145 | * 启动应用的设置
146 | */
147 | private void startAppSettings() {
148 | Intent intent = new Intent(
149 | Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
150 | intent.setData(Uri.parse("package:" + getPackageName()));
151 | startActivity(intent);
152 | }
153 |
154 | @Override
155 | protected void onDestroy() {
156 | ButterKnife.unbind(this);
157 | super.onDestroy();
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/easydb/src/main/java/com/easydblib/handler/EasyDBProxyHandler.java:
--------------------------------------------------------------------------------
1 | package com.easydblib.handler;
2 |
3 | import android.database.sqlite.SQLiteDatabase;
4 | import android.database.sqlite.SQLiteDiskIOException;
5 | import android.util.Log;
6 |
7 | import com.easydblib.EasyDBConfig;
8 | import com.easydblib.dao.RealBaseDao;
9 | import com.easydblib.helper.BaseDBHelper;
10 | import com.easydblib.info.Result;
11 | import com.j256.ormlite.dao.Dao;
12 | import com.j256.ormlite.table.TableUtils;
13 |
14 | import java.lang.reflect.InvocationHandler;
15 | import java.lang.reflect.Method;
16 | import java.lang.reflect.Proxy;
17 | import java.sql.SQLException;
18 |
19 | /**
20 | * @author : zhousf
21 | * @description : 数据库操作代理类:主要进行预处理、日志打印
22 | * @date : 2017/5/23.
23 | */
24 | @SuppressWarnings(value = "all")
25 | public class EasyDBProxyHandler implements InvocationHandler {
26 |
27 | private Object obj;
28 | private BaseDBHelper helper;
29 | private Dao dao;
30 | private Class mClass;
31 | private String databaseName;
32 |
33 | public EasyDBProxyHandler(BaseDBHelper helper,Dao dao, Class mClass, String databaseName) {
34 | this.helper = helper;
35 | this.dao = dao;
36 | this.mClass = mClass;
37 | this.databaseName = databaseName;
38 | }
39 |
40 | public RealBaseDao getProxy(Object targetObject) {
41 | this.obj = targetObject;
42 | Object proxy = Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
43 | targetObject.getClass().getInterfaces(), this);
44 | return (RealBaseDao)proxy;
45 | }
46 |
47 | @Override
48 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
49 | long startTime = getTime();
50 | doBefore();
51 | Object result = method.invoke(obj, args);
52 | doAfter(method,result,startTime);
53 | return result;
54 | }
55 |
56 | /**
57 | * 执行前操作
58 | */
59 | private void doBefore(){
60 | prepareDeal();
61 | }
62 |
63 | /**
64 | * 执行后操作
65 | */
66 | private void doAfter(Method method, Object result, long startTime){
67 | if(result != null){
68 | if(result instanceof Result){
69 | Result real = (Result) result;
70 | String methodName = method.getName();
71 | if(Result.LINE == real.getType()){
72 | showLog(methodName+"["+(getTime()-startTime)+"ms] 影响行数:"+real.getLine());
73 | }else if(Result.COUNT == real.getType()){
74 | showLog(methodName+"["+(getTime()-startTime)+"ms] 影响行数:"+real.getCount());
75 | }else if(Result.LIST == real.getType()){
76 | showLog(methodName+"["+(getTime()-startTime)+"ms] 影响行数:"+real.getList().size());
77 | }else if(Result.IS_EXIST == real.getType()){
78 | showLog(methodName+"["+(getTime()-startTime)+"ms] :"+real.isExist());
79 | }else{
80 | showLog(methodName+"["+(getTime()-startTime)+"ms] ");
81 | }
82 | //异常处理
83 | Exception exception = real.getException();
84 | if(exception != null){
85 | if(exception instanceof ClassCastException){
86 | showErr("列值类型不正确:"+ exception.getMessage());
87 | }
88 | exception.printStackTrace();
89 | }
90 | }
91 | }
92 | }
93 |
94 | /**
95 | * 预处理
96 | */
97 | private void prepareDeal(){
98 | checkTable();
99 | }
100 |
101 | /**
102 | * 检查数据表
103 | */
104 | private void checkTable(){
105 | try {
106 | if(!dao.isTableExists()){
107 | TableUtils.createTableIfNotExists(dao.getConnectionSource(),mClass);
108 | }
109 | } catch (Exception e) {
110 | if(e instanceof SQLiteDiskIOException){
111 | //当用户误删除.db数据库文件时进行数据库恢复(若.db-journal日志文件删除则无法恢复)
112 | // helper.onOpen(helper.getWritableDatabase());
113 | SQLiteDatabase db = helper.getWritableDatabase();
114 | helper.getWritableDatabase().openOrCreateDatabase(db.getPath(),null);
115 | try {
116 | dao = helper.getDao(mClass);
117 | if(!dao.isTableExists()){
118 | TableUtils.createTableIfNotExists(dao.getConnectionSource(),mClass);
119 | }
120 | } catch (SQLException e1) {
121 | e1.printStackTrace();
122 | }
123 | showErr("恢复数据库:"+databaseName);
124 | }else{
125 | e.printStackTrace();
126 | }
127 | }
128 | }
129 |
130 | private long getTime(){
131 | return System.currentTimeMillis();
132 | }
133 |
134 | /**
135 | * 打印日志
136 | */
137 | private void showLog(String msg){
138 | if(EasyDBConfig.showDBLog)
139 | Log.d(EasyDBConfig.logTAG,msg+" | "+mClass.getSimpleName()+" | "+databaseName);
140 | }
141 |
142 | private void showErr(String msg){
143 | if(EasyDBConfig.showDBLog)
144 | Log.e(EasyDBConfig.logTAG,msg+" | "+mClass.getSimpleName()+" | "+databaseName);
145 | }
146 |
147 |
148 |
149 |
150 |
151 | }
152 |
153 |
154 |
155 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
13 |
17 |
24 |
31 |
32 |
36 |
43 |
50 |
51 |
55 |
62 |
69 |
70 |
74 |
81 |
88 |
89 |
93 |
100 |
107 |
108 |
112 |
118 |
124 |
125 |
129 |
135 |
136 |
142 |
143 |
--------------------------------------------------------------------------------
/app/src/main/java/com/easydb/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.easydb.demo;
2 |
3 | import android.os.Bundle;
4 | import android.view.View;
5 | import android.widget.TextView;
6 |
7 | import com.easydb.R;
8 | import com.easydb.core.BaseActivity;
9 | import com.easydb.demo.model.SimpleData;
10 | import com.easydb.util.LogUtil;
11 | import com.easydblib.callback.EasyRun;
12 | import com.easydblib.dao.DBDao;
13 | import com.easydblib.helper.DBHelper;
14 | import com.easydblib.info.OrderInfo;
15 | import com.easydblib.info.WhereInfo;
16 |
17 | import java.util.ArrayList;
18 | import java.util.List;
19 | import java.util.concurrent.Callable;
20 |
21 | import butterknife.Bind;
22 | import butterknife.OnClick;
23 |
24 | public class MainActivity extends BaseActivity {
25 |
26 | private final String TAG = this.getClass().getSimpleName();
27 |
28 | @Bind(R.id.tvResult)
29 | TextView tvResult;
30 |
31 | DBDao dao;
32 |
33 | @Override
34 | protected int initLayout() {
35 | return R.layout.activity_main;
36 | }
37 |
38 | @Override
39 | protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | dao = DBHelper.get().dao(SimpleData.class);
42 | }
43 |
44 | @OnClick({R.id.createBtn, R.id.queryBtn, R.id.queryWhereBtn, R.id.queryPageBtn,
45 | R.id.updateBtn, R.id.deleteBtn, R.id.countBtn, R.id.isExistBtn,
46 | R.id.clearTableBtn, R.id.likeBtn, R.id.batchBtn, R.id.asyncBtn,
47 | R.id.dropBtn })
48 | public void onClick(View view) {
49 | List list;
50 | switch (view.getId()) {
51 | case R.id.createBtn:
52 | //增加
53 | List addList = new ArrayList<>();
54 | for (int i = 1; i <= 20; i++) {
55 | if(i % 2 == 0){
56 | addList.add(new SimpleData(i,"信息"+i));
57 | }else{
58 | addList.add(new SimpleData(i,"我是"+i));
59 | }
60 | }
61 | int line = dao.add(addList);
62 | tvResult.setText("增加总条数:"+line);
63 | break;
64 | case R.id.queryBtn:
65 | //查询
66 | list = dao.queryAll(OrderInfo.get().order(SimpleData._id,false));
67 | printList(list);
68 | break;
69 | case R.id.queryWhereBtn:
70 | //多条件查询并排序
71 | list = dao.query(WhereInfo.get().between(SimpleData._index,1,18)
72 | .equal(SimpleData._group1,true)
73 | .order(SimpleData._id, false));
74 | printList(list);
75 | break;
76 | case R.id.queryPageBtn:
77 | //分页查询-每页5条
78 | WhereInfo info = WhereInfo.get().limit(5);
79 | list = dao.queryLimit(info);//第一页查询
80 | printList(list);
81 | List listLimit = dao.queryLimit(info);//第二页查询
82 | printList(listLimit);
83 | break;
84 | case R.id.updateBtn:
85 | //更新-采用事务方式
86 | dao.callInTransaction(new Callable() {
87 | @Override
88 | public SimpleData call() throws Exception {
89 | List list = dao.queryAll();
90 | if(!list.isEmpty()){
91 | SimpleData data = list.get(0);
92 | data.description = "更新内容";
93 | data.index = 500;
94 | dao.update(data);
95 | }
96 | return null;
97 | }
98 | });
99 | break;
100 | case R.id.deleteBtn:
101 | //删除
102 | list = dao.queryAll();
103 | if(!list.isEmpty()){
104 | if(dao.delete(list.get(0))==1){
105 | tvResult.setText("删除成功");
106 | }else{
107 | tvResult.setText("删除失败");
108 | }
109 | }
110 | break;
111 | case R.id.countBtn:
112 | //条目统计
113 | long num = dao.countOf(WhereInfo.get().equal(SimpleData._group1, true));
114 | tvResult.setText("总条数:"+num);
115 | break;
116 | case R.id.isExistBtn:
117 | //是否存在
118 | boolean isExist = dao.isExist(WhereInfo.get().equal(SimpleData._description,"信息1"));
119 | tvResult.setText(isExist?"存在":"不存在");
120 | break;
121 | case R.id.clearTableBtn:
122 | //清空表
123 | int clear = dao.clearTable();
124 | tvResult.setText("清空表:"+clear);
125 | break;
126 | case R.id.likeBtn:
127 | //模糊查询
128 | list = dao.query(WhereInfo.get().like(SimpleData._description,"我是%"));
129 | printList(list);
130 | break;
131 | case R.id.batchBtn:
132 | //批处理
133 | dao.callBatchTasks(new Callable() {
134 | @Override
135 | public SimpleData call() throws Exception {
136 | List list = dao.queryAll();
137 | for(SimpleData data : list){
138 | data.description += "_批处理";
139 | dao.update(data);
140 | }
141 | return null;
142 | }
143 | });
144 | break;
145 | case R.id.asyncBtn:
146 | //异步任务
147 | dao.asyncTask(new EasyRun>(){
148 | //该方法在异步线程中执行
149 | @Override
150 | public List run() throws Exception {
151 | return dao.queryAll();
152 | }
153 | //该方法在UI线程中执行
154 | @Override
155 | public void onMainThread(List data) throws Exception {
156 | printList(data);
157 | }
158 | });
159 | break;
160 | case R.id.dropBtn:
161 | //删除表
162 | dao.dropTable();
163 | break;
164 | }
165 | }
166 |
167 |
168 | void printList(List list) {
169 | StringBuilder builder = new StringBuilder();
170 | for (SimpleData d : list) {
171 | builder.append(d.toString());
172 | builder.append("\n");
173 | }
174 | LogUtil.d(TAG, builder.toString());
175 | tvResult.setText(builder.toString());
176 | }
177 |
178 |
179 | }
180 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # EasyDB
2 | 基于ORMLite封装的数据库操作工具类——致力于最简洁的数据库操作API。
3 | 由于目前流行的数据框架(如Realm、GreenDAO、ObjectBox)在做项目模块架构时都无法使得表模型分散,表管理统一的架构设计,
4 | 所以本框架还是从SQLite出发,综合考量Android Studio应用架构设计思想通过技术封装以实现该目标。
5 |
6 | ## 功能点
7 | * 支持Android Studio多个Module表模型分散,表管理统一
8 | * 支持自定义数据库路径:SD卡或系统
9 | * 支持主键、索引
10 | * 支持增、删、改、查
11 | * 支持多条件查询、排序、统计、清空、是否存在
12 | * 支持批处理、数据库事务操作
13 | * 支持模糊查询like、between、equal、>、<、>=、<=、<>
14 | * 支持分页查询,分页查询只需要定义每页条数即可
15 | * 支持批量处理
16 | * 支持异步任务操作
17 | * 支持数据库升级,使数据库升级更为简洁
18 | * 完整的日志与异常处理
19 | * Android Studio自动生成表字段别名代码
20 | * 后续优化中...
21 |
22 |
23 | ## 引用方式
24 | ### Maven
25 | ```
26 |
27 | com.zhousf.lib
28 | easydb
29 | 1.7.9
30 | pom
31 |
32 | ```
33 | ### Gradle
34 | ```
35 | compile 'com.zhousf.lib:easydb:1.7.9'
36 | ```
37 |
38 | ## 提交记录
39 | * 2016-12-15 项目提交
40 | * 2016-12-20 增加批处理、事务操作功能
41 | * 2016-12-23 增加异步任务功能
42 | * 2016-12-27 扩展更新、删除操作
43 | * 2017-05-23 优化结构,采用动态代理方式
44 | * 2017-06-12 增加自定义数据库路径功能
45 | * 2018-01-11 支持Android Studio多个Module表模型分散,表管理统一
46 |
47 | ## 项目演示DEMO
48 | 项目中已包含所有支持业务的demo,详情请下载项目参考源码。
49 | 所有集成过程只需2步:1、Application初始化;2、编写表模型
50 |
51 | ## Application中配置
52 | ```
53 | DBHelper.builder()
54 | .setDbPath(Environment.getExternalStorageDirectory() + "/easy_db")//数据库保存路径
55 | .setDbName("easy")//数据库名称
56 | .setDbVersion(1)//数据库版本号
57 | .showDBLog(true)//显示数据库操作日志
58 | .setLogTAG("EASY_DB")//日志显示标识
59 | .build(this);
60 | DBHelper.builder().onUpgrade(new IUpgrade() {
61 | @Override
62 | public void upgrade(DBHelper dbHelper, int oldVersion, int newVersion) throws SQLException {
63 | Log.d("upgrade","oldVersion="+oldVersion+",newVersion="+newVersion);
64 | if(oldVersion < 2){
65 | //增加字段ext
66 | dbHelper.addColumn(SimpleData.class,SimpleData._ext,String.class,"100");
67 | }
68 | }
69 | });
70 | ```
71 |
72 |
73 | ## 数据库操作方法
74 | ```
75 | //获取数据库操作接口
76 | BaseDao dao = DBHelper.get().dao(SimpleData.class);
77 |
78 | //增加
79 | int line = dao.add(new SimpleData(1,"信息1"));
80 |
81 | //查询所有
82 | List list = dao.queryAll();
83 |
84 | //多条件查询并排序
85 | List list = dao.query(WhereInfo.get().between(SimpleData._index,1,18)
86 | .equal("group1",true).order(SimpleData._id, false));
87 |
88 | //分页查询-每页5条
89 | WhereInfo info = WhereInfo.get().limit(5);
90 | List list = dao.queryLimit(info);//第一页查询
91 | list = dao.queryLimit(info);//第二页查询
92 |
93 | //更新
94 | dao.update(data)
95 |
96 | //删除
97 | dao.delete(data)
98 |
99 | //条目统计
100 | long num = dao.countOf(WhereInfo.get().equal(SimpleData._group1, true));
101 |
102 | //是否存在
103 | boolean isExist = dao.isExist(WhereInfo.get().equal(SimpleData._description,"信息2"));
104 |
105 | //清空表
106 | int line = dao.clearTable();
107 |
108 | //批处理-批量操作消耗性能最低
109 | dao.callBatchTasks(new Callable() {
110 | @Override
111 | public SimpleData call() throws Exception {
112 | List list = dao.queryAll();
113 | for(SimpleData data : list){
114 | data.description += "_批处理";
115 | dao.update(data);
116 | }
117 | return null;
118 | }
119 | });
120 |
121 | //更新-采用事务方式,自动回滚
122 | dao.callInTransaction(new Callable() {
123 | @Override
124 | public SimpleData call() throws Exception {
125 | List list = dao.queryAll();
126 | if(!list.isEmpty()){
127 | SimpleData data = list.get(0);
128 | data.description = "更新内容";
129 | dao.update(data);
130 | }
131 | return null;
132 | }
133 | });
134 |
135 | //删除表
136 | int clear = dao.dropTable();
137 |
138 | /**
139 | * 异步任务方式一:在Activity/Fragment中尽量采用异步任务操作数据库
140 | * 异步任务可以重写run方法和onMainThread方法,可根据业务自定义重写方式
141 | **/
142 | dao.asyncTask(new EasyRun>(){
143 | //该方法在异步线程中执行
144 | @Override
145 | public List run() throws Exception {
146 | return dao.queryAll();
147 | }
148 | //该方法在UI线程中执行
149 | @Override
150 | public void onMainThread(List data) throws Exception {
151 | printList(data);
152 | }
153 | });
154 | //异步任务方式二
155 | dao.asyncTask(new EasyRun