I am trying to optimize inserts from a returned JSON which contains data from multiple tables on the remote server. My code is working, but I just want to figure out a way for it to work better. I need the structure to be very dynamic (i.e. fetching the table names from JSON then looping through to complete the inserts into SQLite). This is so if a table is added in the future, I will not have to change any code.
private boolean prepReturnedData(String newString) throws JSONException {
long errCheck = 0; // tracks valid db inserts.
JSONArray columns = new JSONArray();
JSONObject jsonObj = new JSONObject(newString);
ArrayList<String> tables = new ArrayList<String>();
Iterator<?> tableKeys = jsonObj.keys();
while (tableKeys.hasNext()) {
tables.add(tableKeys.next().toString());
}
for (String table : tables) { // Loop through table names.
columns = jsonObj.getJSONArray(table);
for (int index = 0; index < columns.length(); index++) { // Loop through Array of Entries
ContentValues cv = new ContentValues(); // Figure out where to put this.
Iterator<?> iter = columns.getJSONObject(index).keys(); // Creates an Iterator containing Column names.
JSONObject newObj = columns.getJSONObject(index); // Creates a new JSONObject for retrieving column values.
while (iter.hasNext()) { // Iterates to get Column names.
String tColumn = iter.next().toString(); // Stores column name, for retrieval of column value.
cv.put(tColumn, newObj.get(tColumn).toString());
} // end column iterator loop.
String status = null;
if (table == "Seizures") {
status = "timestamp";
} else {
status = "name";
}
try {
SQLiteDatabase db = this.getWritableDatabase();
errCheck = db.replace(table, status, cv);
if (db.isOpen()); {db.close(); };
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end entry loop
} // end table loop
if (errCheck >= 0) {
return true;
} else {
return false;
}
}
This function is within a DatabaseHelper
class.