# ffsky-app-database **Repository Path**: hljdrl/ffsky-app-database ## Basic Information - **Project Name**: ffsky-app-database - **Description**: android sqlite table数据库,sqlite加密数据库,kv数据存储 - **Primary Language**: Android - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-01-07 - **Last Updated**: 2026-02-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ffsky-app-database ## Introduction ffsky-app-database is a lightweight Android local database component built on the **SQLCipher** encryption engine, providing out-of-the-box key-value storage and multi-user settings management. ### Key Features - **Database Encryption** — Full database file encryption via SQLCipher, preventing data from being read after decompilation or root access - **KV Key-Value Storage** — Built-in `KVTable` for one-line key-value CRUD operations, supporting String / int / long / float / double / boolean type reads - **Multi-User Settings Isolation** — Built-in `SettingTable` that automatically isolates user configuration data by account; switching accounts switches data - **Auto Initialization** — Automatic database initialization on app startup via `ContentProvider`, zero-code integration - **Custom Table Extension** — Extend `AbstractTable` or `AbstractAccountTable` to quickly define business data tables - **Incremental Column Upgrade** — `checkTableColumn` + `addTableColumn` mechanism for adding columns without manual version migration - **WAL Concurrency Optimization** — Write-Ahead Logging mode enabled by default, reads and writes never block each other - **Thread Safety** — Database read/write operations protected by `synchronized`, singletons use static inner class / volatile + synchronized patterns ### Architecture Overview ``` ┌─────────────────────────────────────────────────┐ │ Application Layer │ │ KVTable.getInstance().saveItem("k","v") │ │ SettingTable.getInstance().readItem("k","") │ └──────────────────┬──────────────────────────────┘ │ ┌──────────────────▼──────────────────────────────┐ │ DataBaseManager │ │ install() → onLoad() → checkTables() │ │ getWritableDatabase() / getReadableDatabase() │ └──────────────────┬──────────────────────────────┘ │ ┌──────────────────▼──────────────────────────────┐ │ SQLCipher (Encryption Layer) │ │ SQLiteOpenHelper → Encrypted R/W → WAL Mode │ └──────────────────┬──────────────────────────────┘ │ ┌──────────────────▼──────────────────────────────┐ │ SQLite Database File (.db) │ └─────────────────────────────────────────────────┘ ``` --- ## Design Philosophy ### Minimalist API The application layer only needs `getInstance()` + `saveItem()` / `readItem()` and a few other methods — no need to worry about database connections, transactions, or cursor management. One line of code for data access, reducing cognitive overhead for business developers. ### Out of the Box Two commonly used tables are built in: `KVTable` (global key-value) and `SettingTable` (multi-user settings), covering over 90% of lightweight local storage scenarios. Auto-initialization via `ContentProvider` means it works immediately after integration — no manual initialization code in `Application` needed. ### Security First SQLCipher provides full database file encryption. Even if the device is rooted or the database file is extracted, plaintext data cannot be read directly. The encryption password supports external injection; it is recommended to combine it with the Android Keystore for dynamic retrieval. ### Native Multi-User Support The `AbstractAccountTable` base class has a built-in `account` field. Combined with `AccountCache` for globally caching the current user identity, all read/write operations are automatically isolated per user — switching accounts requires only a single `setCacheAccount()` call, with no changes to any business query logic. ### Progressive Extension - **Need more tables?** Extend `AbstractTable` to define your own business tables, register with `addTable()` + `checkTable()` in two steps - **Need new columns?** Override `checkTableColumn()` and use `addTableColumn()` for lossless incremental upgrades - **Need version upgrades?** Override `migrate()` to customize migration strategy; default is DROP + recreate for simplicity ### Lightweight & Non-Invasive The entire library consists of only 8 Java classes with no third-party dependencies (except SQLCipher). No annotation processors, code generation, or reflection — zero compilation overhead, minimal APK size impact. As a public component, it can be directly referenced by any Android project. --- ## API Class & Method Index ### DatabaseTable (Interface) Database table interface defining table lifecycle methods. | Method | Description | |--------|-------------| | `create(SQLiteDatabase db)` | Create the database table | | `migrate(SQLiteDatabase db, int toVersion)` | Database version upgrade migration | | `clear()` | Clear all data in the table | | `checkTableColumn(SQLiteDatabase db, String tableName)` | Check and complete table columns | ### AbstractTable (Abstract Class, implements DatabaseTable) Abstract base class for data tables, providing common CRUD helper methods. | Method | Description | |--------|-------------| | `getTableName()` | Get table name (subclass implementation) | | `getProjection()` | Get column name array (subclass implementation) | | `getListOrder()` | Get default sort order | | `migrate(SQLiteDatabase db, int toVersion)` | Default migration (DROP TABLE) | | `getStringValue(Cursor cursor, String columnName)` | Get string value from Cursor | | `getIntValue(Cursor cursor, String columnName)` | Get int value from Cursor | | `list()` | Query all data | | `list(String select, String[] selectionArgs)` | Query with conditions | | `list(String select, String[] selectionArgs, String groupBy)` | Query with conditions (with grouping) | | `list(String select, String[] selectionArgs, String groupBy, String order)` | Query with conditions (with grouping and sorting) | | `getCount()` | Get total record count | | `clear()` | Clear table data | | `addTableColumn(SQLiteDatabase db, String tableName, String columnName, String sql)` | Add new column (schema upgrade) | | `checkColumnExist(SQLiteDatabase db, String tableName, String columnName)` | Check if column exists | | `checkColumnExistsAsSqliteMaster(SQLiteDatabase db, String tableName, String columnName)` | Check if column exists (via sqlite_master) | | `checkTableColumn(SQLiteDatabase db, String tableName)` | Check table columns (subclass override) | | `readItem(String name)` | Read raw value (subclass override) | | `readItemAsString(String name, String defaultValue)` | Read as String | | `readItemAsInt(String name, int defaultValue)` | Read as int | | `readItemAsLong(String name, long defaultValue)` | Read as long | | `readItemAsFloat(String name, float defaultValue)` | Read as float | | `readItemAsDouble(String name, double defaultValue)` | Read as double | | `readItemAsBoolean(String name, boolean defaultValue)` | Read as boolean | | `hasData(Cursor c)` | Check if Cursor has data | | `closeCursor(Cursor c)` | Safely close Cursor | | `string(String... str)` | Concatenate strings | | `string(Object... str)` | Concatenate object strings | ### AbstractAccountTable (Abstract Class, extends AbstractTable) Abstract base class for multi-user data tables, adding an account field for data isolation. | Method | Description | |--------|-------------| | `removeAccount(String account)` | Remove all data for the specified account | | `getAccount(Cursor cursor)` | Read account identifier from Cursor | ### DataBaseManager (extends SQLiteOpenHelper) Database manager responsible for creation, upgrades, table registration, and lifecycle management. | Method | Description | |--------|-------------| | `install(Context ctx, String dbName, int dbVersion, String dbPassword)` | Initialize database (static, thread-safe) | | `getInstance()` | Get singleton instance | | `unInstance()` | Destroy singleton | | `reInit(Context ctx, String name)` | Re-initialize | | `setPassword(String password)` | Set encryption password | | `getWritableDatabase()` | Get writable database (thread-safe) | | `getReadableDatabase()` | Get readable database (thread-safe) | | `addTable(DatabaseTable table)` | Register a custom table | | `onLoad()` | Load database (enable WAL, create tables, check columns) | | `onClear()` | Clear all table data | | `checkTables()` | Check and complete all registered tables | | `checkTable(AbstractTable table)` | Check and complete a single table | | `tableIsExist(SQLiteDatabase db, String tableName)` | Check if table exists | | `tablesInDB(SQLiteDatabase db)` | Get all table names in database | | `removeAccount(String account)` | Remove account data from all multi-user tables | | `execSQL(SQLiteDatabase db, String sql)` | Execute raw SQL | | `dropTable(SQLiteDatabase db, String table)` | Drop table | | `renameTable(SQLiteDatabase db, String table, String newTable)` | Rename table | ### KVTable (extends AbstractTable) Key-value (KV) data table for storing simple key-value data. | Method | Description | |--------|-------------| | `getInstance()` | Get singleton instance | | `create(SQLiteDatabase db)` | Create KV table | | `saveItem(String key, String body)` | Save data (upsert) | | `deleteItem(String key)` | Delete by key | | `deleteLikeItem(String key)` | Fuzzy delete | | `hasItem(String key)` | Find record ID for key | | `hasKeyValue(String key)` | Check if key exists | | `readMap()` | Read all data as Map | | `readItem(String key, String defaultValue)` | Read value for key | | `readItemInt(String key, int defaultValue)` | Read as int (deprecated) | | `readItemAsString(String name, String defaultValue)` | Read as String (inherited) | | `readItemAsInt(String name, int defaultValue)` | Read as int (inherited) | | `readItemAsLong(String name, long defaultValue)` | Read as long (inherited) | | `readItemAsFloat(String name, float defaultValue)` | Read as float (inherited) | | `readItemAsDouble(String name, double defaultValue)` | Read as double (inherited) | | `readItemAsBoolean(String name, boolean defaultValue)` | Read as boolean (inherited) | ### SettingTable (extends AbstractAccountTable) User settings data table with multi-user data isolation. | Method | Description | |--------|-------------| | `getInstance()` | Get singleton instance | | `create(SQLiteDatabase db)` | Create settings table | | `saveItem(String key, String body)` | Save setting (upsert) | | `deleteItem(String key)` | Delete key for current account | | `hasItem(String key)` | Find record ID for current account's key | | `hasKeyValue(String key)` | Check if key exists for current account | | `readItem(String name, String defaultValue)` | Read value for current account's key | | `removeAccount()` | Remove all data for current account | | `readItemAsString(String name, String defaultValue)` | Read as String (inherited) | | `readItemAsInt(String name, int defaultValue)` | Read as int (inherited) | | `readItemAsLong(String name, long defaultValue)` | Read as long (inherited) | | `readItemAsFloat(String name, float defaultValue)` | Read as float (inherited) | | `readItemAsDouble(String name, double defaultValue)` | Read as double (inherited) | | `readItemAsBoolean(String name, boolean defaultValue)` | Read as boolean (inherited) | ### AccountCache Current account cache for identifying the logged-in user in multi-user scenarios. | Method | Description | |--------|-------------| | `setCacheAccount(String account)` | Set current account identifier | | `getCacheAccount()` | Get current account identifier | ### DatabaseInitProvider (extends ContentProvider) Auto-initialization Provider that completes database initialization on app startup. | Method | Description | |--------|-------------| | `onCreate()` | Called automatically by the system; reads meta-data configuration and initializes the database | --- ## Usage ### Import ```gradle // 2.0.0 Major Update: // AGP upgraded to 8.x, compileSdk/targetSdk to 35, Java 17 // Added DatabaseInitProvider for automatic initialization on app startup // Enabled WAL mode for concurrent read/write without blocking // saveItem uses INSERT OR REPLACE atomic upsert with UNIQUE constraints // Thread safety: volatile singleton, synchronized R/W, Holder singleton pattern // Resource leak fix: all Cursor operations protected by try-finally // readItemAs* methods moved to AbstractTable base class, eliminating duplication // StringBuffer → StringBuilder, DatabaseTable interface made public // Complete Chinese Javadoc for all classes and methods api "com.gitee.hljdrl:database:2.0.0" // Added SettingTable, user settings table extending AbstractAccountTable for multi-user environments // KVTable added: readItemAsString, readItemAsInt, readItemAsLong, readItemAsFloat, readItemAsDouble, readItemAsBoolean api "com.gitee.hljdrl:database:1.0.1" api "com.gitee.hljdrl:database:1.0.0" ``` ### Initialize Database ```java DataBaseManager.install(activity.getApplication(), "database.db", 1, null); ``` ### Load Database Tables Should be called after privacy agreement consent, depending on your app's business requirements. ```java DataBaseManager.getInstance().onLoad(); ``` ### Table Operations ```java // Save data KVTable.getInstance().saveItem("app_set", System.currentTimeMillis() + ""); // Read data String readItem = KVTable.getInstance().readItem("app_set", null); // Clear all data KVTable.getInstance().clear(); ``` ### Custom Tables Extend `AbstractTable` or `AbstractAccountTable` to create your own tables. ```java package com.ffsky.template.demo.table; import android.content.ContentValues; import android.provider.BaseColumns; import com.gitee.hljdrl.database.AbstractTable; import com.gitee.hljdrl.database.DataBaseManager; import net.sqlcipher.Cursor; import net.sqlcipher.database.SQLiteDatabase; public class CacheTable extends AbstractTable { public static final class Fields implements BaseColumns { public static final String TAB_NAME = "_CacheTable" ; // public static final String DATA_KEY = "_DATA_KEY" ; public static final String DATA_BODY = "_DATA_JSON" ; public static final String COLUMNS[] = {_ID,DATA_KEY,DATA_BODY}; } private static CacheTable instance; public static CacheTable getInstance() { if(instance==null){ instance = new CacheTable(); } return instance; } private CacheTable() { } @Override public void create(SQLiteDatabase db) { String sql; sql = "CREATE TABLE " + CacheTable.Fields.TAB_NAME + " (" + CacheTable.Fields._ID+ " INTEGER PRIMARY KEY," + CacheTable.Fields.DATA_KEY + " TEXT," + CacheTable.Fields.DATA_BODY + " TEXT);"; DataBaseManager.execSQL(db, sql); } public int saveItem(String key, String body){ ContentValues cv = new ContentValues(); cv.put(CacheTable.Fields.DATA_KEY, key); cv.put(CacheTable.Fields.DATA_BODY, body); SQLiteDatabase db = DataBaseManager.getInstance().getWritableDatabase(); int $id = hasItem(key); if($id>-1){ int $rid = db.update(getTableName(), cv, CacheTable.Fields._ID+"=?", new String[]{String.valueOf($id)}); return $rid; }else{ long id = db.insert(getTableName(), null, cv); return (int) id; } } public int deleteItem(String key){ try { SQLiteDatabase db = DataBaseManager.getInstance().getWritableDatabase(); int _id = db.delete(getTableName(), CacheTable.Fields.DATA_KEY + "=?", new String[]{key}); return _id; }catch (Exception ex){ } return 0; } public int hasItem(String key){ SQLiteDatabase db = DataBaseManager.getInstance().getReadableDatabase(); Cursor c = db.query(getTableName(), getProjection(), CacheTable.Fields.DATA_KEY+"=?", new String[]{key}, null, null, null); if (hasData(c)) { c.moveToFirst(); int _id = c.getInt(c.getColumnIndex(CacheTable.Fields._ID)); closeCursor(c); return _id; } else { closeCursor(c); return -1; } } public String readItem(String _key,String _default) { String _result = _default; Cursor c = list(CacheTable.Fields.DATA_KEY+"=?",new String[]{_key}); try{ if(c!=null && c.getCount()>0){ c.moveToFirst(); String $body = getStringValue(c, CacheTable.Fields.DATA_BODY); _result = $body; } }finally { closeCursor(c); } return _result; } @Override protected String getTableName() { return CacheTable.Fields.TAB_NAME; } @Override protected String[] getProjection() { return CacheTable.Fields.COLUMNS; } } ``` ### Register Custom Table ```java DataBaseManager.getInstance().addTable(CacheTable.getInstance()); DataBaseManager.getInstance().checkTable(CacheTable.getInstance()); CacheTable.getInstance().saveItem("json", "save-json"); String var = CacheTable.getInstance().readItem("json", null); Toast.makeText(activity, " read: " + var, Toast.LENGTH_SHORT).show(); ```