【问题标题】:Splitting sqlite files for syncing拆分 sqlite 文件以进行同步
【发布时间】:2017-01-15 10:42:45
【问题描述】:
我正在编写一个从传感器收集数据并将其存储在本地 SQLite 数据库中的 Android 应用程序。
我想做的是将此数据(阅读:上传)与后端应用程序同步(我为此使用 Android 的同步适配器)。
由于可以在同步过程中获取数据,所以我认为将 sqlite 文件的最大大小设置为 700 Kb(其实并不重要)是合理的,因此 Sync Adapter 会同步那些 700 Kb 的文件(通过 POST 请求)不包括活动的。一旦 sqlite 文件达到限制,我将创建一个新的活动 sqlite db 并写入它。
如何实现?或许,有更好的解决方案?
【问题讨论】:
标签:
android
sqlite
split
http-post
android-syncadapter
【解决方案1】:
- 最终我决定只使用一个带有“synced_at”字段的数据库文件。
- 我还使用WAL 读取数据(要同步),同时将新数据写入数据库。
- MySQLiteHelper 类是使用单例模式实现的,因此在我的例子中,您可以从主活动和同步适配器同时访问您的数据库。
- 我还在将数据发送到服务器之前对其进行压缩(对于文本,我使用 gzip 实现了 5 倍压缩)。
数据pojo:
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@Setter
public class Data {
private long id;
private float a;
private float b;
private float c;
private long timestamp;
private long synced_at;
}
MySQLiteHelper:
public class MySQLiteHelper extends SQLiteOpenHelper {
private static MySQLiteHelper sInstance;
public static final String DB_NAME = "db.sqlite";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME = "data";
public static synchronized MySQLiteHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new MySQLiteHelper(context.getApplicationContext());
}
return sInstance;
}
private MySQLiteHelper(Context context) {
super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" + DB_NAME,
null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createDbSql = "...";
sqLiteDatabase.execSQL(createDbSql);
Log.d("log", "db created");
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
Log.d("log", "db opened");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
Log.d("log", "db upgraded");
}
}