我正在从应用程序中的 ajax 调用接收 JSONArray
数据。在我的应用程序中的 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
在后台线程中执行所有这些操作。
希望有帮助。
关于java - Android 批量插入或忽略 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55941368/