如何在Android中批量从Json插入到Sqlite

Gee*_*ese 6 sql sqlite android json

如何有效地将来自服务器的批量json数据插入到Android中的Sqlite数据库中.我现在使用的方法效率非常低,完成大约2000条记录的插入需要几分钟.我遵循的方法是:

   for (int i = 0; i < jsonObj.length(); i++) 
{
    JSONObject itemObj = (JSONObject) jsonObj.get(i);

    ContentValues value1 = new ContentValues();
    ContentValues value2 = new ContentValues();

    value2.put(DbHelper.BusinessID,itemObj.getString("BusinessID"));
    value2.put(DbHelper.LocationID,itemObj.getString("LocationID"));
    JSONArray list = itemObj.getJSONArray("OfficeDetails");

    if (list != null) 
    {
    for (int k = 0; k < list.length(); k++) 
    {
        JSONObject elem = list.getJSONObject(k);
        if (elem != null) 
        {
            try 
            {
                value1.put(DbHelper.Office_Code,elem.getInt("Office_Code"));
                value1.put(DbHelper.Office_District,elem.getInt("Office_District"));

                db.insert(DbHelper.MessageDetail,null, value1);
            } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    db.insert(DbHelper.Message,null, value2);
}
Run Code Online (Sandbox Code Playgroud)

即将推出的输入是一个嵌套的Json数组,它本身是嵌套的.有没有更好的方法在很短的时间内快速插入大量数据?

zoz*_*lfo 0

您可以尝试bulkInsert如下操作:

ContentResolver.bulkInsert (Uri url, ContentValues[] values); //Array of rows to be inserted
Run Code Online (Sandbox Code Playgroud)

这仅适用于您仅使用 1 个 URI 的情况,如果您打算使用多个 URI,则应applyBatchContentResolver.

希望能帮助到你