Insert JSON to SQLite table on Android

i have a JSONObject :

{"Table1":[{"row1":"1","B":"2"},{"row2":"1","B1":"2"}],"Table2":[{"C":"1","D":"1145"},{"C":"1","D":"1145"}],"Table3":[{"E":"62","F":"1"},{"C":"1","D":"1145"}]}

how can I insert into sqlite foreach table ?

now use this code:

 for (Iterator<String> iterator = mJson.keys(); iterator.hasNext(); ) {
                    String tableName = iterator.next();
                    if (mJson.optJSONArray(tableName) != null) {
                        resetTable(tableName);
                        JSONArray tableArray = mJson.optJSONArray(tableName);
                        for (int i = 0; i < tableArray.length(); i++) {
                            JSONObject tableData = tableArray.getJSONObject(i);
                            ContentValues Values = new ContentValues();
                            for (Iterator<String> iter = tableData.keys(); iter.hasNext(); ) {
                                String key = iter.next();
                                Values.put(key, tableData.get(key).toString());
                            }
                            db.insert(tableName, null, Values);
                        }
                    }
                }

but i want fastest and better way

Answer

Use bulk insert:

for (Iterator<String> iterator = mJson.keys(); iterator.hasNext(); ) {
    String tableName = iterator.next();
    if (mJson.optJSONArray(tableName) != null) {
        resetTable(tableName);
        String sql = "INSERT INTO " + tableName + " VALUES (?);";
        SQLiteStatement statement = db.compileStatement(sql);
        db.beginTransaction();
        JSONArray tableArray = mJson.optJSONArray(tableName);
        for (int i = 0; i < tableArray.length(); i++) {
            JSONObject tableData = tableArray.getJSONObject(i);
            for (Iterator<String> iter = tableData.keys(); iter.hasNext(); ) {
                String key = iter.next();
                statement.clearBindings();
                statement.bindString(1,tableData.get(key).toString());
                statement.execute();
            }
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *