Example usage for android.content ContentValues containsKey

List of usage examples for android.content ContentValues containsKey

Introduction

In this page you can find the example usage for android.content ContentValues containsKey.

Prototype

public boolean containsKey(String key) 

Source Link

Document

Returns true if this object has the named value.

Usage

From source file:at.bitfire.vcard4android.AndroidContact.java

protected void populateRelation(ContentValues row) {
    String name = row.getAsString(Relation.NAME);

    if (TextUtils.isEmpty(name))
        return;/*from   w  ww. jav a  2s  . c om*/

    Related related = new Related();
    related.setText(name);

    if (row.containsKey(Relation.TYPE))
        switch (row.getAsInteger(Relation.TYPE)) {
        case Relation.TYPE_ASSISTANT:
        case Relation.TYPE_MANAGER:
            related.addType(RelatedType.CO_WORKER);
            break;
        case Relation.TYPE_BROTHER:
        case Relation.TYPE_SISTER:
            related.addType(RelatedType.SIBLING);
            break;
        case Relation.TYPE_CHILD:
            related.addType(RelatedType.CHILD);
            break;
        case Relation.TYPE_DOMESTIC_PARTNER:
            related.addType(RelatedType.CO_RESIDENT);
            break;
        case Relation.TYPE_FRIEND:
            related.addType(RelatedType.FRIEND);
            break;
        case Relation.TYPE_FATHER:
        case Relation.TYPE_MOTHER:
        case Relation.TYPE_PARENT:
            related.addType(RelatedType.PARENT);
            break;
        case Relation.TYPE_PARTNER:
        case Relation.TYPE_SPOUSE:
            related.addType(RelatedType.SWEETHEART);
            break;
        case Relation.TYPE_RELATIVE:
            related.addType(RelatedType.KIN);
            break;
        }

    contact.getRelations().add(related);
}

From source file:org.runnerup.view.DetailActivity.java

void fillHeaderData() {
    // Fields from the database (projection)
    // Must include the _id column for the adapter to work
    String[] from = new String[] { DB.ACTIVITY.START_TIME, DB.ACTIVITY.DISTANCE, DB.ACTIVITY.TIME,
            DB.ACTIVITY.COMMENT, DB.ACTIVITY.SPORT };

    Cursor c = mDB.query(DB.ACTIVITY.TABLE, from, "_id == " + mID, null, null, null, null, null);
    c.moveToFirst();/*ww w  .j  a  v a  2  s.  c  om*/
    ContentValues tmp = DBHelper.get(c);
    c.close();

    long st = 0;
    if (tmp.containsKey(DB.ACTIVITY.START_TIME)) {
        st = tmp.getAsLong(DB.ACTIVITY.START_TIME);
        setTitle("RunnerUp - " + formatter.formatDateTime(Formatter.TXT_LONG, st));
    }
    float d = 0;
    if (tmp.containsKey(DB.ACTIVITY.DISTANCE)) {
        d = tmp.getAsFloat(DB.ACTIVITY.DISTANCE);
        activityDistance.setText(formatter.formatDistance(Formatter.TXT_LONG, (long) d));
    } else {
        activityDistance.setText("");
    }

    float t = 0;
    if (tmp.containsKey(DB.ACTIVITY.TIME)) {
        t = tmp.getAsFloat(DB.ACTIVITY.TIME);
        activityTime.setText(formatter.formatElapsedTime(Formatter.TXT_SHORT, (long) t));
    } else {
        activityTime.setText("");
    }

    if (d != 0 && t != 0) {
        activityPace.setText(formatter.formatPace(Formatter.TXT_LONG, t / d));
    } else {
        activityPace.setText("");
    }

    if (tmp.containsKey(DB.ACTIVITY.COMMENT)) {
        notes.setText(tmp.getAsString(DB.ACTIVITY.COMMENT));
    }

    if (tmp.containsKey(DB.ACTIVITY.SPORT)) {
        sport.setValue(tmp.getAsInteger(DB.ACTIVITY.SPORT));
    }
}

From source file:at.bitfire.vcard4android.AndroidContact.java

protected void populateIMPP(ContentValues row) {
    String handle = row.getAsString(Im.DATA);

    if (TextUtils.isEmpty(handle)) {
        Constants.log.warn("Ignoring instant messenger record without handle");
        return;//w w  w  .  ja v  a2s . com
    }

    Impp impp = null;
    if (row.containsKey(Im.PROTOCOL))
        switch (row.getAsInteger(Im.PROTOCOL)) {
        case Im.PROTOCOL_AIM:
            impp = Impp.aim(handle);
            break;
        case Im.PROTOCOL_MSN:
            impp = Impp.msn(handle);
            break;
        case Im.PROTOCOL_YAHOO:
            impp = Impp.yahoo(handle);
            break;
        case Im.PROTOCOL_SKYPE:
            impp = Impp.skype(handle);
            break;
        case Im.PROTOCOL_QQ:
            impp = new Impp("qq", handle);
            break;
        case Im.PROTOCOL_GOOGLE_TALK:
            impp = new Impp("google-talk", handle);
            break;
        case Im.PROTOCOL_ICQ:
            impp = Impp.icq(handle);
            break;
        case Im.PROTOCOL_JABBER:
            impp = Impp.xmpp(handle);
            break;
        case Im.PROTOCOL_NETMEETING:
            impp = new Impp("netmeeting", handle);
            break;
        case Im.PROTOCOL_CUSTOM:
            try {
                impp = new Impp(toURIScheme(row.getAsString(Im.CUSTOM_PROTOCOL)), handle);
            } catch (IllegalArgumentException e) {
                Constants.log.error("Messenger type/value can't be expressed as URI; ignoring");
            }
        }

    if (impp != null) {
        Integer type = row.getAsInteger(Im.TYPE);
        if (type != null)
            switch (type) {
            case Im.TYPE_HOME:
                impp.addType(ImppType.HOME);
                break;
            case Im.TYPE_WORK:
                impp.addType(ImppType.WORK);
                break;
            case Im.TYPE_CUSTOM:
                String customType = row.getAsString(Im.LABEL);
                if (!TextUtils.isEmpty(customType))
                    impp.addType(ImppType.get(labelToXName(customType)));
            }

        contact.getImpps().add(impp);
    }
}

From source file:com.openerp.orm.ORM.java

/**
 * Creates the.//from   w  w w.ja  v  a 2s.c o m
 * 
 * @param dbHelper
 *            the db helper
 * @param values
 *            the values
 * @return the int
 */
public int create(BaseDBHelper dbHelper, ContentValues data_values) {
    int newId = 0;
    ContentValues values = new ContentValues();
    if (data_values.containsKey("id")) {
        newId = data_values.getAsInteger("id");
    } else {
        newId = createRecordOnserver(dbHelper, data_values);
        data_values.put("id", newId);
    }

    for (Fields field : dbHelper.getColumns()) {
        values.put(field.getName(), data_values.getAsString(field.getName()));
    }

    values.put("oea_name", OpenERPAccountManager.currentUser(context).getAndroidName());

    // Handling Many2Many Records
    HashMap<String, Object> many2manycols = dbHelper.getMany2ManyColumns();
    for (String key : many2manycols.keySet()) {
        try {
            JSONArray m2mArray = new JSONArray(values.getAsString(key));
            Many2Many m2m = (Many2Many) many2manycols.get(key);
            createM2MRecords(values.getAsString("id"), m2mArray, key, dbHelper, m2m, values);
        } catch (Exception e) {
        }
        values.remove(key);
    }

    // Handling Many2One Record
    HashMap<String, Object> many2onecols = dbHelper.getMany2OneColumns();
    for (String key : many2onecols.keySet()) {
        try {
            if (!values.getAsString(key).equals("false")) {
                JSONArray m2oArray = new JSONArray(values.getAsString(key));
                values.put(key, many2oneRecord(m2oArray));
                List<Integer> list = new ArrayList<Integer>();
                int m2o_id = Integer.parseInt(many2oneRecord(m2oArray));
                list.add(m2o_id);
                BaseDBHelper m2oDb = ((Many2One) many2onecols.get(key)).getM2OObject();
                if (!m2oDb.hasRecord(m2oDb, m2o_id)) {
                    oe_obj.syncReferenceTables(m2oDb, list, false);
                }
            }
        } catch (Exception e) {
        }

    }

    SQLiteDatabase db = getWritableDatabase();
    db.insert(modelToTable(dbHelper.getModelName()), null, values);
    db.close();
    return newId;
}

From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java

/** {@inheritDoc} */
@Override/*from www . j  av  a 2s.c  om*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    int drink_id = 0;
    JSONObject result = parser.getJSONObject("result");
    JSONArray drinks = result.getJSONArray("drinks");
    JSONObject drink;
    for (int i = 0; i < drinks.length(); i++) {
        if (drink_id == 0) { // && ENTRY.equals(parser.getName()
            // Process single spreadsheet row at a time
            drink = drinks.getJSONObject(i);
            final String drinkId = sanitizeId(drink.getString("id"));
            final Uri drinkUri = Drinks.buildDrinkUri(drinkId);

            // Check for existing details, only update when changed
            final ContentValues values = queryDrinkDetails(drinkUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found drink " + drinkId);
                Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
            }
            if (localUpdated != KegbotContract.UPDATED_NEVER)
                continue;

            final Uri drinkKegUri = Drinks.buildKegUri(drinkId);
            final Uri drinkUserUri = Drinks.buildUserUri(drinkId);

            // Clear any existing values for this session, treating the
            // incoming details as authoritative.
            batch.add(ContentProviderOperation.newDelete(drinkUri).build());
            batch.add(ContentProviderOperation.newDelete(drinkKegUri).build());

            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Drinks.CONTENT_URI);

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Drinks.DRINK_ID, drinkId);

            // Inherit starred value from previous row
            if (values.containsKey(Drinks.DRINK_STARRED)) {
                builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED));
            }

            if (drink.has("session_id"))
                builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id"));
            if (drink.has("status"))
                builder.withValue(Drinks.STATUS, drink.getString("status"));
            if (drink.has("user_id"))
                builder.withValue(Drinks.USER_ID, drink.getString("user_id"));
            if (drink.has("keg_id"))
                builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id"));
            if (drink.has("volume_ml"))
                builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml"));
            if (drink.has("pour_time"))
                builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time"));

            // Normal session details ready, write to provider
            batch.add(builder.build());

            // Assign kegs
            final int kegId = drink.getInt("keg_id");
            batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId)
                    .withValue(DrinksKeg.KEG_ID, kegId).build());

            // Assign users
            if (drink.has("user_id")) {
                final String userId = drink.getString("user_id");
                batch.add(ContentProviderOperation.newInsert(drinkUserUri)
                        .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build());
            }
        }
    }

    return batch;
}

From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java

/**
 * Synchronize with server when data changes
 *//*from   www  .jav  a  2s . co  m*/
public void pushUpdateOnSave(Update update, ContentValues values, Bitmap imageData) {
    if (!values.containsKey(Update.MESSAGE.name))
        return;

    ArrayList<Object> params = new ArrayList<Object>();
    params.add("message");
    params.add(update.getValue(Update.MESSAGE));

    if (update.getValue(Update.TAGS).length() > 0) {
        String tagId = update.getValue(Update.TAGS);
        tagId = tagId.substring(1, tagId.indexOf(',', 1));
        params.add("tag_id");
        params.add(tagId);
    }

    if (update.getValue(Update.TASK) > 0) {
        params.add("task_id");
        params.add(update.getValue(Update.TASK));
    }
    MultipartEntity picture = null;
    if (imageData != null) {
        picture = buildPictureData(imageData);
    }
    if (!checkForToken())
        return;

    try {
        params.add("token");
        params.add(token);
        JSONObject result;
        if (picture == null)
            result = actFmInvoker.invoke("comment_add", params.toArray(new Object[params.size()]));
        else
            result = actFmInvoker.post("comment_add", picture, params.toArray(new Object[params.size()]));
        update.setValue(Update.REMOTE_ID, result.optLong("id"));
        ImageDiskCache imageCache = ImageDiskCache.getInstance();
        //TODO figure out a way to replace local image files with the url
        String commentPicture = result.optString("picture");
        if (!TextUtils.isEmpty(commentPicture)) {
            String cachedPicture = update.getValue(Update.PICTURE);
            if (!TextUtils.isEmpty(cachedPicture) && imageCache.contains(cachedPicture)) {
                imageCache.move(update.getValue(Update.PICTURE), commentPicture);
            }
            update.setValue(Update.PICTURE, result.optString("picture"));
        }

        updateDao.saveExisting(update);
    } catch (IOException e) {
        if (notPermanentError(e))
            addFailedPush(new FailedPush(PUSH_TYPE_UPDATE, update.getId()));
        handleException("task-save", e);
    }
}

From source file:org.kontalk.provider.UsersProvider.java

private Uri insertOrUpdateKey(String jid, String fingerprint, ContentValues values, boolean insertOnly) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    if (jid == null || fingerprint == null)
        throw new IllegalArgumentException("either JID or fingerprint not provided");

    int rows = 0;

    try {/*from   www.j  av  a2 s  .  c om*/
        // try to insert the key with the provided values
        ContentValues insertValues = new ContentValues(values);
        insertValues.put(Keys.JID, jid);
        insertValues.put(Keys.FINGERPRINT, fingerprint);
        // use current timestamp if the caller didn't provide any
        long timestamp = values.containsKey(Keys.TIMESTAMP) ? values.getAsLong(Keys.TIMESTAMP)
                : System.currentTimeMillis();
        insertValues.put(Keys.TIMESTAMP, timestamp);
        db.insertOrThrow(TABLE_KEYS, null, insertValues);
        rows = 1;
    } catch (SQLiteConstraintException e) {
        if (!insertOnly) {
            // we got a duplicated key, update the requested values
            rows = db.update(TABLE_KEYS, values, Keys.JID + "=? AND " + Keys.FINGERPRINT + "=?",
                    new String[] { jid, fingerprint });
        }
    }

    if (rows >= 0)
        return Keys.CONTENT_URI.buildUpon().appendPath(jid).appendPath(fingerprint).build();
    return null;
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public synchronized int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs);
    WebLoggerIf logger = WebLogger.getLogger(pf.appName);

    /*// ww  w .  j  ava  2 s .com
     * First, find out what records match this query. Replicate the 
     * ContentValues if there are multiple tableIds/formIds involved
     * and the contentValues do not have formId and tableId specified.
     * 
     * Otherwise, it is an error to specify the tableId or formId in
     * the ContentValues and have those not match the where results.
     * 
     */
    String contentTableId = (values != null && values.containsKey(FormsColumns.TABLE_ID))
            ? values.getAsString(FormsColumns.TABLE_ID)
            : null;
    String contentFormId = (values != null && values.containsKey(FormsColumns.FORM_ID))
            ? values.getAsString(FormsColumns.FORM_ID)
            : null;

    HashMap<FormSpec, HashMap<String, Object>> matchedValues = new HashMap<FormSpec, HashMap<String, Object>>();

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        Cursor c = null;
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, null, pf.whereId, pf.whereIdArgs, null, null, null,
                    null);

            if (c == null) {
                throw new SQLException(
                        "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
            }
            if (c.moveToFirst()) {
                int idxId = c.getColumnIndex(FormsColumns._ID);
                int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID);
                int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID);

                Integer idValue = null;
                String tableIdValue = null;
                String formIdValue = null;

                do {
                    idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId);
                    tableIdValue = CursorUtils.getIndexAsString(c, idxTableId);
                    formIdValue = CursorUtils.getIndexAsString(c, idxFormId);

                    if (contentTableId != null && !contentTableId.equals(tableIdValue)) {
                        throw new SQLException("Modification of tableId for an existing form is prohibited");
                    }
                    if (contentFormId != null && !contentFormId.equals(formIdValue)) {
                        throw new SQLException("Modification of formId for an existing form is prohibited");
                    }

                    HashMap<String, Object> cv = new HashMap<String, Object>();
                    if (values != null) {
                        for (String key : values.keySet()) {
                            cv.put(key, values.get(key));
                        }
                    }
                    cv.put(FormsColumns.TABLE_ID, tableIdValue);
                    cv.put(FormsColumns.FORM_ID, formIdValue);
                    for (int idx = 0; idx < c.getColumnCount(); ++idx) {
                        String colName = c.getColumnName(idx);
                        if (colName.equals(FormsColumns._ID)) {
                            // don't insert the PK
                            continue;
                        }

                        if (c.isNull(idx)) {
                            cv.put(colName, null);
                        } else {
                            // everything else, we control...
                            Class<?> dataType = CursorUtils.getIndexDataType(c, idx);
                            if (dataType == String.class) {
                                cv.put(colName, CursorUtils.getIndexAsString(c, idx));
                            } else if (dataType == Long.class) {
                                cv.put(colName, CursorUtils.getIndexAsType(c, Long.class, idx));
                            } else if (dataType == Double.class) {
                                cv.put(colName, CursorUtils.getIndexAsType(c, Double.class, idx));
                            }
                        }
                    }

                    FormSpec formSpec = patchUpValues(pf.appName, cv);
                    formSpec._id = idValue.toString();
                    formSpec.success = false;
                    matchedValues.put(formSpec, cv);

                } while (c.moveToNext());
            } else {
                // no match on where clause...
                return 0;
            }
        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
        }

        // go through the entries and update the database with these patched-up values...

        for (Entry<FormSpec, HashMap<String, Object>> e : matchedValues.entrySet()) {
            FormSpec fs = e.getKey();
            HashMap<String, Object> cv = e.getValue();

            if (db.update(DatabaseConstants.FORMS_TABLE_NAME, cv, FormsColumns._ID + "=?",
                    new String[] { fs._id }) > 0) {
                fs.success = true;
            }
        }
        db.setTransactionSuccessful();

    } catch (Exception e) {
        logger.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
                            .removeConnection(pf.appName, dbHandleName);
                }
            }
        }
    }

    int failureCount = 0;
    for (FormSpec fs : matchedValues.keySet()) {
        if (fs.success) {
            Uri formUri = Uri
                    .withAppendedPath(
                            Uri.withAppendedPath(Uri.withAppendedPath(
                                    Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId),
                            fs.formId);
            getContext().getContentResolver().notifyChange(formUri, null);
            Uri idUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), fs._id);
            getContext().getContentResolver().notifyChange(idUri, null);
        } else {
            ++failureCount;
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);

    int count = matchedValues.size();
    if (failureCount != 0) {
        throw new SQLiteException(
                "Unable to update all forms (" + (count - failureCount) + " of " + count + " updated)");
    }
    return count;
}

From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java

public void initialize() {
    initializeRetryRunnable();/*from   www . j  av  a  2s .c o  m*/

    taskDao.addListener(new ModelUpdateListener<Task>() {
        @Override
        public void onModelUpdated(final Task model) {
            if (model.checkAndClearTransitory(SyncFlags.ACTFM_SUPPRESS_SYNC))
                return;
            if (actFmPreferenceService.isOngoing() && model.getTransitory(TaskService.TRANS_EDIT_SAVE) == null)
                return;
            final ContentValues setValues = model.getSetValues();
            if (setValues == null || !checkForToken()
                    || setValues.containsKey(RemoteModel.REMOTE_ID_PROPERTY_NAME))
                return;
            if (completedRepeatingTask(model))
                return;

            new Thread(new Runnable() {
                @Override
                public void run() {
                    waitUntilEmpty.close();
                    taskPushThreads.incrementAndGet();
                    // sleep so metadata associated with task is saved
                    try {
                        AndroidUtilities.sleepDeep(1000L);
                        pushTaskOnSave(model, setValues);
                    } finally {
                        if (taskPushThreads.decrementAndGet() == 0) {
                            waitUntilEmpty.open();
                        }
                    }
                }
            }).start();
        }

        private boolean completedRepeatingTask(Task model) {
            return !TextUtils.isEmpty(model.getValue(Task.RECURRENCE)) && model.isCompleted();
        }
    });

    updateDao.addListener(new ModelUpdateListener<Update>() {
        @Override
        public void onModelUpdated(final Update model) {
            if (model.checkAndClearTransitory(SyncFlags.ACTFM_SUPPRESS_SYNC))
                return;
            if (actFmPreferenceService.isOngoing())
                return;
            final ContentValues setValues = model.getSetValues();
            if (setValues == null || !checkForToken() || model.getValue(Update.REMOTE_ID) > 0)
                return;

            new Thread(new Runnable() {
                @Override
                public void run() {
                    pushUpdateOnSave(model, setValues, null);
                }
            }).start();
        }
    });

    tagDataDao.addListener(new ModelUpdateListener<TagData>() {
        @Override
        public void onModelUpdated(final TagData model) {
            if (model.checkAndClearTransitory(SyncFlags.ACTFM_SUPPRESS_SYNC))
                return;
            if (actFmPreferenceService.isOngoing())
                return;
            final ContentValues setValues = model.getSetValues();
            if (setValues == null || !checkForToken()
                    || setValues.containsKey(RemoteModel.REMOTE_ID_PROPERTY_NAME))
                return;

            new Thread(new Runnable() {
                @Override
                public void run() {
                    pushTagDataOnSave(model, setValues);
                }
            }).start();
        }
    });
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private ContentValues parseObject(JsonParser parser, SQLiteDatabase tempDb, String parentId, int seq)
        throws JsonParseException, IOException {
    // TODO : Grab id of root topic here, and store it in shared prefs, in case it ever
    //        changes. Currently we assume "root" and a change would be catastrophic.
    ContentValues result = new ContentValues();
    ChildArrayResults childResults = null;
    boolean badKind = false;

    result.put("parentTopic_id", parentId);
    result.put("seq", seq);

    while (parser.nextValue() != JsonToken.END_OBJECT) {

        // Allows us to burn through the rest of the object once we discover it's an exercise or something else we don't care about.
        if (badKind)
            continue;

        String fieldName = parser.getCurrentName();

        // Keys present will determine object type.
        if (stringFields.contains(fieldName)) {
            // Use getValueAsString over getText; getText returns "null" while getValueAsString returns null.
            String value = parser.getValueAsString();
            result.put(fieldName, value);

            if ("id".equals(fieldName)) {
                if (childResults != null) {
                    addParentIdToChildren(tempDb, childResults, value);
                }//from w  ww .  j  a  v  a  2 s .c  o m
            }
        } else if (intFields.contains(fieldName)) {
            result.put(fieldName, parser.getIntValue());
        } else if (booleanFields.contains(fieldName)) {
            result.put(fieldName, parser.getBooleanValue());
        } else if ("children".equals(fieldName)) {
            childResults = parseChildArray(parser, tempDb,
                    result.containsKey("id") ? result.getAsString("id") : null);
            result.put("video_count", childResults.videoCount);
            result.put("child_kind", childResults.childKind);
            result.put("thumb_id", childResults.thumbId);
        } else if ("download_urls".equals(fieldName)) {
            parseDownloadUrls(parser, result);
        } else if (null == fieldName) {
            // Noop. Just in case.
        } else {
            JsonToken next = parser.getCurrentToken();
            if (next == JsonToken.START_OBJECT || next == JsonToken.START_ARRAY) {
                // Skip this object or array, leaving us pointing at the matching end_object / end_array token.
                parser.skipChildren();
            }
        }
    }

    // Ignore types we don't need.
    if (badKind) {
        return null;
    }

    // Having parsed this whole object, we can insert it.
    if (result.containsKey("kind")) {
        String kind = result.getAsString("kind");
        if ("Topic".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("_id", result.getAsString("id"));
                result.remove("id");
            }
            if (result.containsKey("child_kind")) {
                String child_kind = result.getAsString("child_kind");
                if ("Topic".equals(child_kind) || "Video".equals(child_kind)) {
                    insertTopic(tempDb, result);
                }
            }
        } else if ("Video".equals(kind)) {
            if (result.containsKey("id")) {
                result.put("video_id", result.getAsString("id"));
                result.remove("id");
            }
            insertTopicVideo(tempDb, result);
            insertVideo(tempDb, result);
        }
    }

    return result;
}