java - Android 批量插入或忽略 JSONArray
问题描述
我正在JSONArray
从我的应用程序中的 ajax 调用接收数据。在我的应用程序中的 SQLite 表上执行插入/冲突跳过的最佳方法是什么?我有以下代码:
try {
JSONArray data = response.getJSONArray("data");
ContentValues contentValues = new ContentValues();
// I don't know what to do here.
// Do I do a for loop and convert the entire JSONArray into ContentValues
// with the column name and value for each item in the array?
db.insertWithOnConflict("Data", null, data, SQLiteDatabase.CONFLICT_IGNORE);
} catch (JSONException e) {
e.printStackTrace();
}
解决方案
是的,您必须编写一个循环来转换JSONArray
要插入数据库的数据。如果您使用可以自动执行此操作的库,它实际上并没有减少数据处理的时间,对吧?
但是,您可以通过一个单一的数据库事务来最小化对数据库表的插入操作,如下所示。
SQLiteDatabase db = ...
db.beginTransaction();
try {
// do ALL your inserts here
db.setTransactionSuccessful()
} finally {
db.endTransaction();
}
您也可以考虑使用一个AsyncTask
在后台线程中执行所有这些操作。
希望有帮助。
推荐阅读
- git - 我应该提交包含 firestore 初始化配置的 environment.ts 文件吗
- javascript - 没有使用 $(this) 提醒第二个 div 的内容
- apache-spark - spark退出状态中的-1000是什么意思
- google-app-engine - 使用 Appengine 标准用户登录服务,如何提示更长的登录登录间隔?
- r - 如何在R中绘制相关矩阵与变量之间已经导出的相关值?
- c++ - 我不明白这个向量声明语句
- android - 无法在 Android Studio 3.5 中创建数字表盘
- selenium - 删除重复的 TestNG Cucumber Runner 文件
- php - 使用 ajax 显示搜索结果
- python - 生成与趋势相关的数据