【问题标题】:Android bulk insert or ignore JSONArrayAndroid 批量插入或忽略 JSONArray
【发布时间】:2019-09-20 07:43:05
【问题描述】:

我从我的应用程序中的 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();
}

【问题讨论】:

  • 所以,网络和数据库是两个不同的东西,你应该养成不要混用它们的习惯。话虽如此,序列化您的响应可能更容易,因此您不必手动搜索JSONArrayJSONObject 中的字段。假设您确实想继续反对我给您的两个建议,JSONArrays 是一个列表,因此它们没有每个项目的名称(这将是一个地图)。循环 JSONArray 就像循环 List 一样(尽管有一些限制): for(int i = 0; i

标签: java android arrays sqlite insert


【解决方案1】:

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

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

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

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

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多