From 09ca816223d379f3eb0bf376682b5f4f69d398df Mon Sep 17 00:00:00 2001 From: AriaLyy <511455842@qq.com> Date: Fri, 7 Apr 2017 16:30:58 +0800 Subject: [PATCH] =?UTF-8?q?302=E8=B7=B3=E8=BD=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Aria/build.gradle | 4 +- .../orm/{DBMapping.java => DBConfig.java} | 24 +- .../java/com/arialyy/aria/orm/DbEntity.java | 11 +- .../java/com/arialyy/aria/orm/DbUtil.java | 356 +------------- .../java/com/arialyy/aria/orm/SqlHelper.java | 448 ++++++++++++++++-- README.md | 3 +- app/build.gradle | 1 + 7 files changed, 451 insertions(+), 396 deletions(-) rename Aria/src/main/java/com/arialyy/aria/orm/{DBMapping.java => DBConfig.java} (58%) diff --git a/Aria/build.gradle b/Aria/build.gradle index 1fa8d679..81393a41 100644 --- a/Aria/build.gradle +++ b/Aria/build.gradle @@ -7,8 +7,8 @@ android { defaultConfig { minSdkVersion 9 targetSdkVersion 23 - versionCode 100 - versionName "3.0.0" + versionCode 101 + versionName "3.0.2" } buildTypes { release { diff --git a/Aria/src/main/java/com/arialyy/aria/orm/DBMapping.java b/Aria/src/main/java/com/arialyy/aria/orm/DBConfig.java similarity index 58% rename from Aria/src/main/java/com/arialyy/aria/orm/DBMapping.java rename to Aria/src/main/java/com/arialyy/aria/orm/DBConfig.java index 54dda504..8f2ed69c 100644 --- a/Aria/src/main/java/com/arialyy/aria/orm/DBMapping.java +++ b/Aria/src/main/java/com/arialyy/aria/orm/DBConfig.java @@ -15,18 +15,32 @@ */ package com.arialyy.aria.orm; +import android.text.TextUtils; +import com.arialyy.aria.core.download.DownloadEntity; +import com.arialyy.aria.core.upload.UploadEntity; import java.util.HashMap; import java.util.Map; /** * Created by Aria.Lao on 2017/4/6. - * DB映射表 + * 数据库配置信息 */ -public class DBMapping { - static Map mapping = new HashMap<>(); +public class DBConfig { + static Map mapping = new HashMap<>(); + static String DB_NAME; + static int VERSION = 2; static { - mapping.put("DownloadEntity", "com.arialyy.aria.core.download.DownloadEntity"); - mapping.put("UploadEntity", "com.arialyy.aria.core.upload.UploadEntity"); + if (TextUtils.isEmpty(DB_NAME)) { + DB_NAME = "AriaLyyDb"; + } + if (VERSION == -1) { + VERSION = 1; + } + } + + static { + mapping.put("DownloadEntity", DownloadEntity.class); + mapping.put("UploadEntity", UploadEntity.class); } } diff --git a/Aria/src/main/java/com/arialyy/aria/orm/DbEntity.java b/Aria/src/main/java/com/arialyy/aria/orm/DbEntity.java index e39df929..4378c2d8 100644 --- a/Aria/src/main/java/com/arialyy/aria/orm/DbEntity.java +++ b/Aria/src/main/java/com/arialyy/aria/orm/DbEntity.java @@ -29,7 +29,6 @@ import java.util.List; public class DbEntity { private static final Object LOCK = new Object(); protected int rowID = -1; - private DbUtil mUtil = DbUtil.getInstance(); protected DbEntity() { @@ -84,14 +83,14 @@ public class DbEntity { * 获取所有行的rowid */ public int[] getRowIds() { - return mUtil.getRowId(getClass()); + return DbUtil.getInstance().getRowId(getClass()); } /** * 获取rowid */ public int getRowId(@NonNull Object[] wheres, @NonNull Object[] values) { - return mUtil.getRowId(getClass(), wheres, values); + return DbUtil.getInstance().getRowId(getClass(), wheres, values); } /** @@ -117,7 +116,7 @@ public class DbEntity { * 修改数据 */ public void update() { - mUtil.modifyData(this); + DbUtil.getInstance().modifyData(this); } /** @@ -125,7 +124,7 @@ public class DbEntity { */ public void save() { synchronized (LOCK) { - if (mUtil.tableExists(getClass()) && thisIsExist()) { + if (DbUtil.getInstance().tableExists(getClass()) && thisIsExist()) { update(); } else { insert(); @@ -144,7 +143,7 @@ public class DbEntity { * 插入数据 */ public void insert() { - mUtil.insertData(this); + DbUtil.getInstance().insertData(this); updateRowID(); } diff --git a/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java b/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java index 1e691daa..0e14dea1 100644 --- a/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java +++ b/Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java @@ -38,13 +38,6 @@ public class DbUtil { private static final String TAG = "DbUtil"; private static final Object LOCK = new Object(); private volatile static DbUtil INSTANCE = null; - private static final int CREATE_TABLE = 0; - private static final int TABLE_EXISTS = 1; - private static final int INSERT_DATA = 2; - private static final int MODIFY_DATA = 3; - private static final int FIND_DATA = 4; - private static final int FIND_ALL_DATA = 5; - private int DEL_DATA = 6; private int ROW_ID = 7; private SQLiteDatabase mDb; private SqlHelper mHelper; @@ -54,12 +47,7 @@ public class DbUtil { } private DbUtil(Context context) { - //mHelper = new SqlHelper(context.getApplicationContext(), new SqlHelper.UpgradeListener() { - // @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - // - // } - //}); - mHelper = new SqlHelper(context.getApplicationContext()); + mHelper = SqlHelper.init(context.getApplicationContext()); } public static DbUtil init(Context context) { @@ -80,48 +68,13 @@ public class DbUtil { return INSTANCE; } - /** - * 删除某条数据 - */ - @Deprecated private synchronized void delData(Class clazz, - @NonNull Object[] wheres, @NonNull Object[] values) { - mDb = mHelper.getWritableDatabase(); - if (wheres.length <= 0 || values.length <= 0) { - Log.e(TAG, "输入删除条件"); - return; - } else if (wheres.length != values.length) { - Log.e(TAG, "key 和 vaule 长度不相等"); - return; - } - StringBuilder sb = new StringBuilder(); - sb.append("DELETE FROM ").append(CommonUtil.getClassName(clazz)).append(" WHERE "); - int i = 0; - for (Object where : wheres) { - sb.append(where).append("=").append("'").append(values[i]).append("'"); - sb.append(i >= wheres.length - 1 ? "" : ","); - i++; - } - print(DEL_DATA, sb.toString()); - mDb.execSQL(sb.toString()); - close(); - } - /** * 删除某条数据 */ synchronized void delData(Class clazz, String... expression) { CheckUtil.checkSqlExpression(expression); mDb = mHelper.getWritableDatabase(); - String sql = "DELETE FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " "; - sql = sql.replace("?", "%s"); - Object[] params = new String[expression.length - 1]; - for (int i = 0, len = params.length; i < len; i++) { - params[i] = "'" + expression[i + 1] + "'"; - } - sql = String.format(sql, params); - print(DEL_DATA, sql); - mDb.execSQL(sql); - close(); + SqlHelper.delData(mDb, clazz, expression); } /** @@ -129,34 +82,7 @@ public class DbUtil { */ synchronized void modifyData(DbEntity dbEntity) { mDb = mHelper.getWritableDatabase(); - Class clazz = dbEntity.getClass(); - Field[] fields = CommonUtil.getFields(clazz); - if (fields != null && fields.length > 0) { - StringBuilder sb = new StringBuilder(); - sb.append("UPDATE ").append(CommonUtil.getClassName(dbEntity)).append(" SET "); - int i = 0; - for (Field field : fields) { - field.setAccessible(true); - if (ignoreField(field)) { - continue; - } - sb.append(i > 0 ? ", " : ""); - try { - Object value = field.get(dbEntity); - sb.append(field.getName()) - .append("='") - .append(value == null ? "" : value.toString()) - .append("'"); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - i++; - } - sb.append(" where rowid=").append(dbEntity.rowID); - print(MODIFY_DATA, sb.toString()); - mDb.execSQL(sb.toString()); - } - close(); + SqlHelper.modifyData(mDb, dbEntity); } /** @@ -166,43 +92,15 @@ public class DbUtil { if (mDb == null || !mDb.isOpen()) { mDb = mHelper.getReadableDatabase(); } - return findAllData(mDb, clazz); - } - - /** - * 遍历所有数据 - */ - static synchronized List findAllData(SQLiteDatabase db, Class clazz) { - if (!tableExists(db, clazz)) { - createTable(db, clazz, null); - } - StringBuilder sb = new StringBuilder(); - sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz)); - print(FIND_ALL_DATA, sb.toString()); - Cursor cursor = db.rawQuery(sb.toString(), null); - return cursor.getCount() > 0 ? newInstanceEntity(db, clazz, cursor) : null; + return SqlHelper.findAllData(mDb, clazz); } /** * 条件查寻数据 */ synchronized List findData(Class clazz, String... expression) { - if (!tableExists(clazz)) { - createTable(clazz); - } mDb = mHelper.getReadableDatabase(); - CheckUtil.checkSqlExpression(expression); - String sql = - "SELECT rowid, * FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " "; - sql = sql.replace("?", "%s"); - Object[] params = new String[expression.length - 1]; - for (int i = 0, len = params.length; i < len; i++) { - params[i] = "'" + expression[i + 1] + "'"; - } - sql = String.format(sql, params); - print(FIND_DATA, sql); - Cursor cursor = mDb.rawQuery(sql, null); - return cursor.getCount() > 0 ? newInstanceEntity(mDb, clazz, cursor) : null; + return SqlHelper.findData(mDb, clazz, expression); } /** @@ -210,72 +108,8 @@ public class DbUtil { */ @Deprecated synchronized List findData(Class clazz, @NonNull String[] wheres, @NonNull String[] values) { - if (!tableExists(clazz)) { - createTable(clazz); - } mDb = mHelper.getReadableDatabase(); - if (wheres.length <= 0 || values.length <= 0) { - Log.e(TAG, "请输入查询条件"); - return null; - } else if (wheres.length != values.length) { - Log.e(TAG, "key 和 vaule 长度不相等"); - return null; - } - StringBuilder sb = new StringBuilder(); - sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz)).append(" where "); - int i = 0; - for (Object where : wheres) { - sb.append(where).append("=").append("'").append(values[i]).append("'"); - sb.append(i >= wheres.length - 1 ? "" : " AND "); - i++; - } - print(FIND_DATA, sb.toString()); - Cursor cursor = mDb.rawQuery(sb.toString(), null); - return cursor.getCount() > 0 ? newInstanceEntity(mDb, clazz, cursor) : null; - } - - /** - * 插入数据 - */ - static synchronized void insertData(SQLiteDatabase db, DbEntity dbEntity) { - Class clazz = dbEntity.getClass(); - if (!tableExists(db, clazz)) { - createTable(db, clazz, null); - } - Field[] fields = CommonUtil.getFields(clazz); - if (fields != null && fields.length > 0) { - StringBuilder sb = new StringBuilder(); - sb.append("INSERT INTO ").append(CommonUtil.getClassName(dbEntity)).append("("); - int i = 0; - for (Field field : fields) { - field.setAccessible(true); - if (ignoreField(field)) { - continue; - } - sb.append(i > 0 ? ", " : ""); - sb.append(field.getName()); - i++; - } - sb.append(") VALUES ("); - i = 0; - for (Field field : fields) { - field.setAccessible(true); - if (ignoreField(field)) { - continue; - } - sb.append(i > 0 ? ", " : ""); - sb.append("'"); - try { - sb.append(field.get(dbEntity)).append("'"); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - i++; - } - sb.append(")"); - print(INSERT_DATA, sb.toString()); - db.execSQL(sb.toString()); - } + return SqlHelper.findData(mDb, clazz, wheres, values); } /** @@ -285,8 +119,7 @@ public class DbUtil { if (mDb == null || !mDb.isOpen()) { mDb = mHelper.getReadableDatabase(); } - insertData(mDb, dbEntity); - close(); + SqlHelper.insertData(mDb, dbEntity); } /** @@ -296,85 +129,14 @@ public class DbUtil { if (mDb == null || !mDb.isOpen()) { mDb = mHelper.getReadableDatabase(); } - return tableExists(mDb, clazz); - } - - static synchronized boolean tableExists(SQLiteDatabase db, Class clazz) { - Cursor cursor = null; - try { - StringBuilder sb = new StringBuilder(); - sb.append("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='"); - sb.append(CommonUtil.getClassName(clazz)); - sb.append("'"); - print(TABLE_EXISTS, sb.toString()); - cursor = db.rawQuery(sb.toString(), null); - if (cursor != null && cursor.moveToNext()) { - int count = cursor.getInt(0); - if (count > 0) { - return true; - } - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (cursor != null) cursor.close(); - if (db != null) { - db.close(); - } - } - return false; - } - - static synchronized void createTable(SQLiteDatabase db, Class clazz, String tableName) { - Field[] fields = CommonUtil.getFields(clazz); - if (fields != null && fields.length > 0) { - StringBuilder sb = new StringBuilder(); - sb.append("create table ") - .append(TextUtils.isEmpty(tableName) ? CommonUtil.getClassName(clazz) : tableName) - .append("("); - for (Field field : fields) { - field.setAccessible(true); - if (ignoreField(field)) { - continue; - } - sb.append(field.getName()); - Class type = field.getType(); - if (type == String.class) { - sb.append(" varchar"); - } else if (type == int.class || type == Integer.class) { - sb.append(" interger"); - } else if (type == float.class || type == Float.class) { - sb.append(" float"); - } else if (type == double.class || type == Double.class) { - sb.append(" double"); - } else if (type == long.class || type == Long.class) { - sb.append(" bigint"); - } else if (type == boolean.class || type == Boolean.class) { - sb.append(" boolean"); - } else if (type == java.util.Date.class || type == java.sql.Date.class) { - sb.append(" data"); - } else if (type == byte.class || type == Byte.class) { - sb.append(" blob"); - } else { - continue; - } - sb.append(","); - } - String str = sb.toString(); - str = str.substring(0, str.length() - 1) + ");"; - print(CREATE_TABLE, str); - db.execSQL(str); - } - if (db != null) { - db.close(); - } + return SqlHelper.tableExists(mDb, clazz); } synchronized void createTable(Class clazz, String tableName) { if (mDb == null || !mDb.isOpen()) { mDb = mHelper.getWritableDatabase(); } - createTable(mDb, clazz, tableName); + SqlHelper.createTable(mDb, clazz, tableName); } /** @@ -384,48 +146,6 @@ public class DbUtil { createTable(clazz, null); } - /** - * @return true 忽略该字段 - */ - static boolean ignoreField(Field field) { - // field.isSynthetic(), 使用as热启动App时,AS会自动给你的clss添加change字段 - Ignore ignore = field.getAnnotation(Ignore.class); - return (ignore != null && ignore.value()) || field.isSynthetic(); - } - - /** - * 打印数据库日志 - * - * @param type {@link DbUtil} - */ - private static void print(int type, String sql) { - if (true) { - return; - } - String str = ""; - switch (type) { - case CREATE_TABLE: - str = "创建表 >>>> "; - break; - case TABLE_EXISTS: - str = "表是否存在 >>>> "; - break; - case INSERT_DATA: - str = "插入数据 >>>> "; - break; - case MODIFY_DATA: - str = "修改数据 >>>> "; - break; - case FIND_DATA: - str = "查询一行数据 >>>> "; - break; - case FIND_ALL_DATA: - str = "遍历整个数据库 >>>> "; - break; - } - Log.v(TAG, str + sql); - } - /** * 关闭数据库 */ @@ -472,67 +192,11 @@ public class DbUtil { sb.append(i >= wheres.length - 1 ? "" : ","); i++; } - print(ROW_ID, sb.toString()); + SqlHelper.print(ROW_ID, sb.toString()); Cursor c = mDb.rawQuery(sb.toString(), null); int id = c.getColumnIndex("rowid"); c.close(); close(); return id; } - - /** - * 根据数据游标创建一个具体的对象 - */ - private static synchronized List newInstanceEntity(SQLiteDatabase db, - Class clazz, Cursor cursor) { - Field[] fields = CommonUtil.getFields(clazz); - List entitys = new ArrayList<>(); - if (fields != null && fields.length > 0) { - try { - while (cursor.moveToNext()) { - T entity = clazz.newInstance(); - for (Field field : fields) { - field.setAccessible(true); - if (ignoreField(field)) { - continue; - } - Class type = field.getType(); - int column = cursor.getColumnIndex(field.getName()); - if (type == String.class) { - field.set(entity, cursor.getString(column)); - } else if (type == int.class || type == Integer.class) { - field.setInt(entity, cursor.getInt(column)); - } else if (type == float.class || type == Float.class) { - field.setFloat(entity, cursor.getFloat(column)); - } else if (type == double.class || type == Double.class) { - field.setDouble(entity, cursor.getDouble(column)); - } else if (type == long.class || type == Long.class) { - field.setLong(entity, cursor.getLong(column)); - } else if (type == boolean.class || type == Boolean.class) { - field.setBoolean(entity, !cursor.getString(column).equalsIgnoreCase("false")); - } else if (type == java.util.Date.class || type == java.sql.Date.class) { - field.set(entity, new Date(cursor.getString(column))); - } else if (type == byte[].class) { - field.set(entity, cursor.getBlob(column)); - } else { - continue; - } - } - entity.rowID = cursor.getInt(cursor.getColumnIndex("rowid")); - entitys.add(entity); - //Log.d(TAG, "rowid ==> " + entity.rowID); - } - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - cursor.close(); - //close(); - if (db != null) { - db.close(); - } - return entitys; - } } \ No newline at end of file diff --git a/Aria/src/main/java/com/arialyy/aria/orm/SqlHelper.java b/Aria/src/main/java/com/arialyy/aria/orm/SqlHelper.java index 23ebf7b0..81bc39d5 100644 --- a/Aria/src/main/java/com/arialyy/aria/orm/SqlHelper.java +++ b/Aria/src/main/java/com/arialyy/aria/orm/SqlHelper.java @@ -20,11 +20,15 @@ import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; +import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.Log; +import com.arialyy.aria.util.CheckUtil; import com.arialyy.aria.util.CommonUtil; -import java.io.File; import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Set; @@ -33,30 +37,30 @@ import java.util.Set; * sql帮助类 */ final class SqlHelper extends SQLiteOpenHelper { - interface UpgradeListener { - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); - } + private static final String TAG = "SqlHelper"; + private static final int CREATE_TABLE = 0; + private static final int TABLE_EXISTS = 1; + private static final int INSERT_DATA = 2; + private static final int MODIFY_DATA = 3; + private static final int FIND_DATA = 4; + private static final int FIND_ALL_DATA = 5; + private static final int DEL_DATA = 6; - private UpgradeListener mUpgradeListener; - static String DB_NAME; - static int VERSION = -1; + private static volatile SqlHelper INSTANCE = null; + private static final Object LOCK = new Object(); - static { - if (TextUtils.isEmpty(DB_NAME)) { - DB_NAME = "AriaLyyDb"; - } - if (VERSION == -1) { - VERSION = 1; + static SqlHelper init(Context context) { + if (INSTANCE == null) { + synchronized (LOCK) { + INSTANCE = new SqlHelper(context.getApplicationContext()); + checkTable(INSTANCE.getWritableDatabase()); + } } + return INSTANCE; } - //SqlHelper(Context context, UpgradeListener listener) { - // super(context, DB_NAME, null, VERSION); - // mUpgradeListener = listener; - //} - - SqlHelper(Context context) { - super(context, DB_NAME, null, VERSION); + private SqlHelper(Context context) { + super(context, DBConfig.DB_NAME, null, DBConfig.VERSION); } @Override public void onCreate(SQLiteDatabase db) { @@ -64,12 +68,15 @@ final class SqlHelper extends SQLiteOpenHelper { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - try { - if (oldVersion < newVersion) { - handleDbUpdate(db); - } - } catch (ClassNotFoundException e) { - e.printStackTrace(); + if (oldVersion < newVersion) { + handleDbUpdate(db); + } + } + + @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { + //super.onDowngrade(db, oldVersion, newVersion); + if (oldVersion > newVersion) { + handleDbUpdate(db); } } @@ -78,7 +85,7 @@ final class SqlHelper extends SQLiteOpenHelper { * * @throws ClassNotFoundException */ - private void handleDbUpdate(SQLiteDatabase db) throws ClassNotFoundException { + private void handleDbUpdate(SQLiteDatabase db) { if (db == null) { Log.d("SqlHelper", "db 为 null"); return; @@ -86,10 +93,11 @@ final class SqlHelper extends SQLiteOpenHelper { Log.d("SqlHelper", "db已关闭"); return; } - Set tables = DBMapping.mapping.keySet(); + Set tables = DBConfig.mapping.keySet(); for (String tableName : tables) { - Class clazz = Class.forName(DBMapping.mapping.get(tableName)); - if (DbUtil.tableExists(db, clazz)) { + Class clazz = DBConfig.mapping.get(tableName); + if (tableExists(db, clazz)) { + //db = checkDb(db); String countColumnSql = "SELECT rowid FROM " + tableName; Cursor cursor = db.rawQuery(countColumnSql, null); int dbColumnNum = cursor.getColumnCount(); @@ -105,24 +113,27 @@ final class SqlHelper extends SQLiteOpenHelper { * 备份 */ private void back(SQLiteDatabase db, Class clazz) { + db = checkDb(db); String oldTableName = CommonUtil.getClassName(clazz); //备份数据 - List list = DbUtil.findAllData(db, clazz); + List list = findAllData(db, clazz); //修改原来表名字 String alertSql = "alter table " + oldTableName + " rename to " + oldTableName + "_temp"; db.beginTransaction(); db.execSQL(alertSql); //创建一个原来新表 - DbUtil.createTable(db, clazz, null); - for (DbEntity entity : list) { - DbUtil.insertData(db, entity); + createTable(db, clazz, null); + if (list != null && list.size() > 0) { + for (DbEntity entity : list) { + insertData(db, entity); + } } //删除原来的表 String deleteSQL = "drop table IF EXISTS " + oldTableName + "_temp"; db.execSQL(deleteSQL); db.setTransactionSuccessful(); db.endTransaction(); - db.close(); + close(db); } /** @@ -134,7 +145,7 @@ final class SqlHelper extends SQLiteOpenHelper { if (fields != null && fields.length > 0) { for (Field field : fields) { field.setAccessible(true); - if (DbUtil.ignoreField(field)) { + if (ignoreField(field)) { continue; } count++; @@ -142,4 +153,369 @@ final class SqlHelper extends SQLiteOpenHelper { } return count; } + + /** + * 检查数据库表,如果配置的表不存在,则创建新表 + */ + static synchronized void checkTable(SQLiteDatabase db) { + db = checkDb(db); + Set tables = DBConfig.mapping.keySet(); + for (String tableName : tables) { + Class clazz = null; + clazz = DBConfig.mapping.get(tableName); + + if (!tableExists(db, clazz)) { + createTable(db, clazz, null); + } + } + } + + /** + * 条件查寻数据 + */ + static synchronized List findData(SQLiteDatabase db, Class clazz, + String... expression) { + db = checkDb(db); + CheckUtil.checkSqlExpression(expression); + String sql = + "SELECT rowid, * FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " "; + sql = sql.replace("?", "%s"); + Object[] params = new String[expression.length - 1]; + for (int i = 0, len = params.length; i < len; i++) { + params[i] = "'" + expression[i + 1] + "'"; + } + sql = String.format(sql, params); + print(FIND_DATA, sql); + Cursor cursor = db.rawQuery(sql, null); + List data = cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null; + close(db); + return data; + } + + /** + * 条件查寻数据 + */ + @Deprecated static synchronized List findData(SQLiteDatabase db, + Class clazz, @NonNull String[] wheres, @NonNull String[] values) { + db = checkDb(db); + if (wheres.length <= 0 || values.length <= 0) { + Log.e(TAG, "请输入查询条件"); + return null; + } else if (wheres.length != values.length) { + Log.e(TAG, "key 和 vaule 长度不相等"); + return null; + } + StringBuilder sb = new StringBuilder(); + sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz)).append(" where "); + int i = 0; + for (Object where : wheres) { + sb.append(where).append("=").append("'").append(values[i]).append("'"); + sb.append(i >= wheres.length - 1 ? "" : " AND "); + i++; + } + print(FIND_DATA, sb.toString()); + Cursor cursor = db.rawQuery(sb.toString(), null); + List data = cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null; + close(db); + return data; + } + + /** + * 遍历所有数据 + */ + static synchronized List findAllData(SQLiteDatabase db, Class clazz) { + db = checkDb(db); + StringBuilder sb = new StringBuilder(); + sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz)); + print(FIND_ALL_DATA, sb.toString()); + Cursor cursor = db.rawQuery(sb.toString(), null); + List data = cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null; + close(db); + return data; + } + + /** + * 删除某条数据 + */ + static synchronized void delData(SQLiteDatabase db, Class clazz, + String... expression) { + db = checkDb(db); + CheckUtil.checkSqlExpression(expression); + String sql = "DELETE FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " "; + sql = sql.replace("?", "%s"); + Object[] params = new String[expression.length - 1]; + for (int i = 0, len = params.length; i < len; i++) { + params[i] = "'" + expression[i + 1] + "'"; + } + sql = String.format(sql, params); + SqlHelper.print(DEL_DATA, sql); + db.execSQL(sql); + close(db); + } + + /** + * 修改某行数据 + */ + static synchronized void modifyData(SQLiteDatabase db, DbEntity dbEntity) { + db = checkDb(db); + Class clazz = dbEntity.getClass(); + Field[] fields = CommonUtil.getFields(clazz); + if (fields != null && fields.length > 0) { + StringBuilder sb = new StringBuilder(); + sb.append("UPDATE ").append(CommonUtil.getClassName(dbEntity)).append(" SET "); + int i = 0; + for (Field field : fields) { + field.setAccessible(true); + if (SqlHelper.ignoreField(field)) { + continue; + } + sb.append(i > 0 ? ", " : ""); + try { + Object value = field.get(dbEntity); + sb.append(field.getName()) + .append("='") + .append(value == null ? "" : value.toString()) + .append("'"); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + i++; + } + sb.append(" where rowid=").append(dbEntity.rowID); + print(MODIFY_DATA, sb.toString()); + db.execSQL(sb.toString()); + } + close(db); + } + + /** + * 插入数据 + */ + static synchronized void insertData(SQLiteDatabase db, DbEntity dbEntity) { + db = checkDb(db); + Class clazz = dbEntity.getClass(); + Field[] fields = CommonUtil.getFields(clazz); + if (fields != null && fields.length > 0) { + StringBuilder sb = new StringBuilder(); + sb.append("INSERT INTO ").append(CommonUtil.getClassName(dbEntity)).append("("); + int i = 0; + for (Field field : fields) { + field.setAccessible(true); + if (ignoreField(field)) { + continue; + } + sb.append(i > 0 ? ", " : ""); + sb.append(field.getName()); + i++; + } + sb.append(") VALUES ("); + i = 0; + for (Field field : fields) { + field.setAccessible(true); + if (ignoreField(field)) { + continue; + } + sb.append(i > 0 ? ", " : ""); + sb.append("'"); + try { + sb.append(field.get(dbEntity)).append("'"); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + i++; + } + sb.append(")"); + print(INSERT_DATA, sb.toString()); + db.execSQL(sb.toString()); + } + close(db); + } + + /** + * 查找表是否存在 + * + * @param clazz 数据库实体 + * @return true,该数据库实体对应的表存在;false,不存在 + */ + static synchronized boolean tableExists(SQLiteDatabase db, Class clazz) { + db = checkDb(db); + Cursor cursor = null; + try { + StringBuilder sb = new StringBuilder(); + sb.append("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='"); + sb.append(CommonUtil.getClassName(clazz)); + sb.append("'"); + print(TABLE_EXISTS, sb.toString()); + cursor = db.rawQuery(sb.toString(), null); + if (cursor != null && cursor.moveToNext()) { + int count = cursor.getInt(0); + if (count > 0) { + return true; + } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (cursor != null) cursor.close(); + close(db); + } + return false; + } + + /** + * 创建表 + * + * @param clazz 数据库实体 + * @param tableName 数据库实体的类名 + */ + static synchronized void createTable(SQLiteDatabase db, Class clazz, String tableName) { + db = checkDb(db); + Field[] fields = CommonUtil.getFields(clazz); + if (fields != null && fields.length > 0) { + StringBuilder sb = new StringBuilder(); + sb.append("create table ") + .append(TextUtils.isEmpty(tableName) ? CommonUtil.getClassName(clazz) : tableName) + .append("("); + for (Field field : fields) { + field.setAccessible(true); + if (ignoreField(field)) { + continue; + } + sb.append(field.getName()); + Class type = field.getType(); + if (type == String.class) { + sb.append(" varchar"); + } else if (type == int.class || type == Integer.class) { + sb.append(" interger"); + } else if (type == float.class || type == Float.class) { + sb.append(" float"); + } else if (type == double.class || type == Double.class) { + sb.append(" double"); + } else if (type == long.class || type == Long.class) { + sb.append(" bigint"); + } else if (type == boolean.class || type == Boolean.class) { + sb.append(" boolean"); + } else if (type == java.util.Date.class || type == java.sql.Date.class) { + sb.append(" data"); + } else if (type == byte.class || type == Byte.class) { + sb.append(" blob"); + } else { + continue; + } + sb.append(","); + } + String str = sb.toString(); + str = str.substring(0, str.length() - 1) + ");"; + print(CREATE_TABLE, str); + db.execSQL(str); + } + close(db); + } + + /** + * 打印数据库日志 + * + * @param type {@link DbUtil} + */ + static void print(int type, String sql) { + if (true) { + return; + } + String str = ""; + switch (type) { + case CREATE_TABLE: + str = "创建表 >>>> "; + break; + case TABLE_EXISTS: + str = "表是否存在 >>>> "; + break; + case INSERT_DATA: + str = "插入数据 >>>> "; + break; + case MODIFY_DATA: + str = "修改数据 >>>> "; + break; + case FIND_DATA: + str = "查询一行数据 >>>> "; + break; + case FIND_ALL_DATA: + str = "遍历整个数据库 >>>> "; + break; + } + Log.v(TAG, str + sql); + } + + /** + * 根据数据游标创建一个具体的对象 + */ + static synchronized List newInstanceEntity(Class clazz, + Cursor cursor) { + Field[] fields = CommonUtil.getFields(clazz); + List entitys = new ArrayList<>(); + if (fields != null && fields.length > 0) { + try { + while (cursor.moveToNext()) { + T entity = clazz.newInstance(); + for (Field field : fields) { + field.setAccessible(true); + if (ignoreField(field)) { + continue; + } + Class type = field.getType(); + int column = cursor.getColumnIndex(field.getName()); + if (column == -1) continue; + if (type == String.class) { + field.set(entity, cursor.getString(column)); + } else if (type == int.class || type == Integer.class) { + field.setInt(entity, cursor.getInt(column)); + } else if (type == float.class || type == Float.class) { + field.setFloat(entity, cursor.getFloat(column)); + } else if (type == double.class || type == Double.class) { + field.setDouble(entity, cursor.getDouble(column)); + } else if (type == long.class || type == Long.class) { + field.setLong(entity, cursor.getLong(column)); + } else if (type == boolean.class || type == Boolean.class) { + field.setBoolean(entity, !cursor.getString(column).equalsIgnoreCase("false")); + } else if (type == java.util.Date.class || type == java.sql.Date.class) { + field.set(entity, new Date(cursor.getString(column))); + } else if (type == byte[].class) { + field.set(entity, cursor.getBlob(column)); + } else { + continue; + } + } + entity.rowID = cursor.getInt(cursor.getColumnIndex("rowid")); + entitys.add(entity); + //Log.d(TAG, "rowid ==> " + entity.rowID); + } + cursor.close(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + return entitys; + } + + private static void close(SQLiteDatabase db) { + //if (db != null && db.isOpen()) db.close(); + } + + private static SQLiteDatabase checkDb(SQLiteDatabase db) { + if (db == null || !db.isOpen()) { + db = INSTANCE.getWritableDatabase(); + } + return db; + } + + /** + * @return true 忽略该字段 + */ + static boolean ignoreField(Field field) { + // field.isSynthetic(), 使用as热启动App时,AS会自动给你的clss添加change字段 + Ignore ignore = field.getAnnotation(Ignore.class); + return (ignore != null && ignore.value()) || field.isSynthetic() || Modifier.isStatic( + field.getModifiers()) || Modifier.isFinal(field.getModifiers()); + } } \ No newline at end of file diff --git a/README.md b/README.md index 7a05bc3b..a41ebaab 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Aria怎样使用? ## 下载 [![Download](https://api.bintray.com/packages/arialyy/maven/Aria/images/download.svg)](https://bintray.com/arialyy/maven/Aria/_latestVersion)
```java -compile 'com.arialyy.aria:Aria:3.0.0' +compile 'com.arialyy.aria:Aria:3.0.2' ``` ## 示例 @@ -143,6 +143,7 @@ compile 'com.arialyy.aria:Aria:3.0.0' *** ## 开发日志 + + v_3.0.2 支持30x重定向链接下载 + v_3.0.0 添加上传任务支持,修复一些已发现的bug + v_2.4.4 修复不支持断点的下载链接拿不到文件大小的问题 + v_2.4.3 修复404链接卡顿的问题 diff --git a/app/build.gradle b/app/build.gradle index b863586e..4eba9ffb 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -38,4 +38,5 @@ dependencies { compile 'com.arialyy.frame:MVVM2:2.2.0' compile 'com.arialyy.absadapter:AbsAdapter:1.1.2' compile project(':Aria') +// compile 'com.arialyy.aria:Aria:3.0.0' }