/** * Given a JSON item and a sync map, create a ContentValues map to be inserted into the DB. * * @param context * @param localItem will be null if item is new to mobile. If it's been sync'd before, will point * to local entry. * @param item incoming JSON item. * @param mySyncMap A mapping between the JSON object and the content values. * @return new ContentValues, ready to be inserted into the database. * @throws JSONException * @throws IOException * @throws NetworkProtocolException */ public static final ContentValues fromJSON( Context context, Uri localItem, JSONObject item, SyncMap mySyncMap) throws JSONException, IOException, NetworkProtocolException { final ContentValues cv = new ContentValues(); for (final String propName : mySyncMap.keySet()) { final SyncItem map = mySyncMap.get(propName); if (!map.isDirection(SyncItem.SYNC_FROM)) { continue; } if (map.isOptional() && (!item.has(map.remoteKey) || item.isNull(map.remoteKey))) { continue; } final ContentValues cv2 = map.fromJSON(context, localItem, item, propName); if (cv2 != null) { cv.putAll(cv2); } } return cv; }
/** * @param context * @param localItem Will contain the URI of the local item being referenced in the cursor * @param c active cursor with the item to sync selected. * @param mySyncMap * @return a new JSONObject representing the item * @throws JSONException * @throws NetworkProtocolException * @throws IOException */ public static final JSONObject toJSON(Context context, Uri localItem, Cursor c, SyncMap mySyncMap) throws JSONException, NetworkProtocolException, IOException { final JSONObject jo = new JSONObject(); for (final String lProp : mySyncMap.keySet()) { final SyncItem map = mySyncMap.get(lProp); if (!map.isDirection(SyncItem.SYNC_TO)) { continue; } final int colIndex = c.getColumnIndex(lProp); // if it's a real property that's optional and is null on the local side if (!lProp.startsWith("_") && map.isOptional()) { if (colIndex == -1) { throw new RuntimeException( "Programming error: Cursor does not have column '" + lProp + "', though sync map says it should. Sync Map: " + mySyncMap); } if (c.isNull(colIndex)) { continue; } } final Object jsonObject = map.toJSON(context, localItem, c, lProp); if (jsonObject instanceof MultipleJsonObjectKeys) { for (final Entry<String, Object> entry : ((MultipleJsonObjectKeys) jsonObject).entrySet()) { jo.put(entry.getKey(), entry.getValue()); } } else { jo.put(map.remoteKey, jsonObject); } } return jo; }