首页 > 解决方案 > 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();
}

标签: javaandroidarrayssqliteinsert

解决方案


是的,您必须编写一个循环来转换JSONArray要插入数据库的数据。如果您使用可以自动执行此操作的库,它实际上并没有减少数据处理的时间,对吧?

但是,您可以通过一个单一的数据库事务来最小化对数据库表的插入操作,如下所示。

SQLiteDatabase db = ...
db.beginTransaction();
try {
    // do ALL your inserts here
    db.setTransactionSuccessful()
} finally {
    db.endTransaction();
}

您也可以考虑使用一个AsyncTask在后台线程中执行所有这些操作。

希望有帮助。


推荐阅读