Example usage for android.content ContentValues getAsString

List of usage examples for android.content ContentValues getAsString

Introduction

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

Prototype

public String getAsString(String key) 

Source Link

Document

Gets a value and converts it to a String.

Usage

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long insertGroup(SQLiteDatabase db, ContentValues cv) {
    try {//  w  ww.j a va 2 s.c  o m
        validate(cv.getAsString(Group.NAME));
        return db.insertOrThrow(Group.TABLE, null, cv);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return -1;
    }
}

From source file:android.pim.vcard.VCardBuilder.java

public VCardBuilder appendNotes(final List<ContentValues> contentValuesList) {
    if (contentValuesList != null) {
        if (mOnlyOneNoteFieldIsAvailable) {
            final StringBuilder noteBuilder = new StringBuilder();
            boolean first = true;
            for (final ContentValues contentValues : contentValuesList) {
                String note = contentValues.getAsString(Note.NOTE);
                if (note == null) {
                    note = "";
                }//from  www  .java2 s . co  m
                if (note.length() > 0) {
                    if (first) {
                        first = false;
                    } else {
                        noteBuilder.append('\n');
                    }
                    noteBuilder.append(note);
                }
            }
            final String noteStr = noteBuilder.toString();
            // This means we scan noteStr completely twice, which is redundant.
            // But for now, we assume this is not so time-consuming..
            final boolean shouldAppendCharsetInfo = !VCardUtils.containsOnlyPrintableAscii(noteStr);
            final boolean reallyUseQuotedPrintable = (mShouldUseQuotedPrintable
                    && !VCardUtils.containsOnlyNonCrLfPrintableAscii(noteStr));
            appendLine(VCardConstants.PROPERTY_NOTE, noteStr, shouldAppendCharsetInfo,
                    reallyUseQuotedPrintable);
        } else {
            for (ContentValues contentValues : contentValuesList) {
                final String noteStr = contentValues.getAsString(Note.NOTE);
                if (!TextUtils.isEmpty(noteStr)) {
                    final boolean shouldAppendCharsetInfo = !VCardUtils.containsOnlyPrintableAscii(noteStr);
                    final boolean reallyUseQuotedPrintable = (mShouldUseQuotedPrintable
                            && !VCardUtils.containsOnlyNonCrLfPrintableAscii(noteStr));
                    appendLine(VCardConstants.PROPERTY_NOTE, noteStr, shouldAppendCharsetInfo,
                            reallyUseQuotedPrintable);
                }
            }
        }
    }
    return this;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long insertSubscriber(SQLiteDatabase db, ContentValues cv) {
    try {//  w w w .  j a v a  2 s  .com
        String feedName = cv.getAsString(Subscriber.FEED_NAME);
        validate(feedName);
        return db.insertOrThrow(Subscriber.TABLE, null, cv);
    } catch (SQLiteConstraintException e) {
        //this inserts dupes, so hide this spam in a way 
        //that doesn't require api level 8
        return -1;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return -1;
    }
}

From source file:com.koushikdutta.superuser.MultitaskSuRequestActivity.java

void manageSocket() {
    new Thread() {
        @Override//from  w ww .ja v  a2 s . co  m
        public void run() {
            try {
                mSocket = new LocalSocket();
                mSocket.connect(new LocalSocketAddress(mSocketPath, Namespace.FILESYSTEM));

                DataInputStream is = new DataInputStream(mSocket.getInputStream());

                ContentValues payload = new ContentValues();

                for (int i = 0; i < SU_PROTOCOL_PARAM_MAX; i++) {
                    int nameLen = is.readInt();
                    if (nameLen > SU_PROTOCOL_NAME_MAX)
                        throw new IllegalArgumentException("name length too long: " + nameLen);
                    byte[] nameBytes = new byte[nameLen];
                    is.readFully(nameBytes);
                    String name = new String(nameBytes);
                    int dataLen = is.readInt();
                    if (dataLen > getValueMax(name))
                        throw new IllegalArgumentException(name + " data length too long: " + dataLen);
                    byte[] dataBytes = new byte[dataLen];
                    is.readFully(dataBytes);
                    String data = new String(dataBytes);
                    payload.put(name, data);
                    //                        Log.i(LOGTAG, name);
                    //                        Log.i(LOGTAG, data);
                    if ("eof".equals(name))
                        break;
                }

                int protocolVersion = payload.getAsInteger("version");
                mCallerUid = payload.getAsInteger("from.uid");
                mDesiredUid = payload.getAsByte("to.uid");
                mDesiredCmd = payload.getAsString("command");
                String calledBin = payload.getAsString("from.bin");
                mPid = payload.getAsInteger("pid");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRequestReady = true;
                        requestReady();
                    }
                });

                if ("com.koushikdutta.superuser".equals(getPackageName())) {
                    if (!SuHelper.CURRENT_VERSION.equals(payload.getAsString("binary.version")))
                        SuCheckerReceiver.doNotification(MultitaskSuRequestActivity.this);
                }
            } catch (Exception ex) {
                Log.i(LOGTAG, ex.getMessage(), ex);
                try {
                    mSocket.close();
                } catch (Exception e) {
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                });
            }
        }
    }.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 . co 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;
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

@Override
public int bulkInsert(final Uri uri, @NonNull final ContentValues[] valuesArray) {
    try {/*from   w w  w.  j  a v a 2 s  .co m*/
        final int tableId = getTableId(uri);
        final String table = getTableNameById(tableId);
        switch (tableId) {
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
        case TABLE_ID_DIRECT_MESSAGES:
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRIES:
            return 0;
        }
        int result = 0;
        final long[] newIds = new long[valuesArray.length];
        if (table != null) {
            mDatabaseWrapper.beginTransaction();
            if (tableId == TABLE_ID_CACHED_USERS) {
                for (final ContentValues values : valuesArray) {
                    final Expression where = Expression.equals(CachedUsers.USER_ID,
                            values.getAsLong(CachedUsers.USER_ID));
                    mDatabaseWrapper.update(table, values, where.getSQL(), null);
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_IGNORE);
                }
            } else if (tableId == TABLE_ID_SEARCH_HISTORY) {
                for (final ContentValues values : valuesArray) {
                    values.put(SearchHistory.RECENT_QUERY, System.currentTimeMillis());
                    final Expression where = Expression.equalsArgs(SearchHistory.QUERY);
                    final String[] args = { values.getAsString(SearchHistory.QUERY) };
                    mDatabaseWrapper.update(table, values, where.getSQL(), args);
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_IGNORE);
                }
            } else if (shouldReplaceOnConflict(tableId)) {
                for (final ContentValues values : valuesArray) {
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_REPLACE);
                }
            } else {
                for (final ContentValues values : valuesArray) {
                    newIds[result++] = mDatabaseWrapper.insert(table, null, values);
                }
            }
            mDatabaseWrapper.setTransactionSuccessful();
            mDatabaseWrapper.endTransaction();
        }
        if (result > 0) {
            onDatabaseUpdated(tableId, uri);
        }
        onNewItemsInserted(uri, tableId, valuesArray, newIds);
        return result;
    } catch (final SQLException e) {
        throw new IllegalStateException(e);
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long insertContact(SQLiteDatabase db, ContentValues cv) {
    try {//  w w  w .j  av a 2  s .co  m
        Log.i(TAG, "Inserting contact: " + cv);
        String pubKeyStr = cv.getAsString(Contact.PUBLIC_KEY);
        assert (pubKeyStr != null) && pubKeyStr.length() > 0;
        PublicKey key = RSACrypto.publicKeyFromString(pubKeyStr);
        cv.put(Contact.PUBLIC_KEY_HASH_64, hashPublicKey(key.getEncoded()));
        String tag = edu.stanford.mobisocial.bumblebee.util.Util.makePersonIdForPublicKey(key);
        cv.put(Contact.PERSON_ID, tag);
        String name = cv.getAsString(Contact.NAME);
        assert (name != null) && name.length() > 0;
        return getWritableDatabase().insertOrThrow(Contact.TABLE, null, cv);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return -1;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

/**
 * Inserts an object into the database and flags it to be sent by
 * the transport layer.//from   ww  w .j ava2  s . c o m
 */
long addToFeed(String appId, String feedName, ContentValues values) {
    try {
        JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
        String type = values.getAsString(DbObject.TYPE);

        long nextSeqId = getFeedMaxSequenceId(Contact.MY_ID, feedName) + 1;
        long timestamp = new Date().getTime();
        json.put(DbObjects.TYPE, type);
        json.put(DbObjects.FEED_NAME, feedName);
        json.put(DbObjects.SEQUENCE_ID, nextSeqId);
        json.put(DbObjects.TIMESTAMP, timestamp);
        json.put(DbObjects.APP_ID, appId);

        // Explicit column referencing avoids database errors.
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, getNextId());
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, Contact.MY_ID);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, nextSeqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());

        if (values.containsKey(DbObject.RAW)) {
            cv.put(DbObject.RAW, values.getAsByteArray(DbObject.RAW));
        }
        if (values.containsKey(DbObject.KEY_INT)) {
            cv.put(DbObject.KEY_INT, values.getAsInteger(DbObject.KEY_INT));
        }
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        Long objId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, objId, relation);
            }
        }

        Uri objUri = DbObject.uriForObj(objId);
        mContext.getContentResolver().registerContentObserver(objUri, false,
                new ModificationObserver(mContext, objId));
        return objId;
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}

From source file:android.pim.vcard.VCardBuilder.java

public VCardBuilder appendPhones(final List<ContentValues> contentValuesList) {
    boolean phoneLineExists = false;
    if (contentValuesList != null) {
        Set<String> phoneSet = new HashSet<String>();
        for (ContentValues contentValues : contentValuesList) {
            final Integer typeAsObject = contentValues.getAsInteger(Phone.TYPE);
            final String label = contentValues.getAsString(Phone.LABEL);
            final Integer isPrimaryAsInteger = contentValues.getAsInteger(Phone.IS_PRIMARY);
            final boolean isPrimary = (isPrimaryAsInteger != null ? (isPrimaryAsInteger > 0) : false);
            String phoneNumber = contentValues.getAsString(Phone.NUMBER);
            if (phoneNumber != null) {
                phoneNumber = phoneNumber.trim();
            }//from w w  w .ja va2  s  .c om
            if (TextUtils.isEmpty(phoneNumber)) {
                continue;
            }
            int type = (typeAsObject != null ? typeAsObject : DEFAULT_PHONE_TYPE);
            if (type == Phone.TYPE_PAGER) {
                phoneLineExists = true;
                if (!phoneSet.contains(phoneNumber)) {
                    phoneSet.add(phoneNumber);
                    appendTelLine(type, label, phoneNumber, isPrimary);
                }
            } else {
                // The entry "may" have several phone numbers when the contact entry is
                // corrupted because of its original source.
                //
                // e.g. I encountered the entry like the following.
                // "111-222-3333 (Miami)\n444-555-6666 (Broward; 305-653-6796 (Miami); ..."
                // This kind of entry is not able to be inserted via Android devices, but
                // possible if the source of the data is already corrupted.
                List<String> phoneNumberList = splitIfSeveralPhoneNumbersExist(phoneNumber);
                if (phoneNumberList.isEmpty()) {
                    continue;
                }
                phoneLineExists = true;
                for (String actualPhoneNumber : phoneNumberList) {
                    if (!phoneSet.contains(actualPhoneNumber)) {
                        final int format = VCardUtils.getPhoneNumberFormat(mVCardType);
                        final String formattedPhoneNumber = PhoneNumberUtils.formatNumber(actualPhoneNumber,
                                format);
                        phoneSet.add(actualPhoneNumber);
                        appendTelLine(type, label, formattedPhoneNumber, isPrimary);
                    }
                }
            }
        }
    }

    if (!phoneLineExists && mIsDoCoMo) {
        appendTelLine(Phone.TYPE_HOME, "", "", false);
    }

    return this;
}

From source file:com.hualu.wifistart.vcardsrc.VCardBuilder.java

public VCardBuilder appendPhones(final List<ContentValues> contentValuesList) {
    boolean phoneLineExists = false;
    if (contentValuesList != null) {
        Set<String> phoneSet = new HashSet<String>();
        for (ContentValues contentValues : contentValuesList) {
            final Integer typeAsObject = contentValues.getAsInteger(Phone.TYPE);
            final String label = contentValues.getAsString(Phone.LABEL);
            final Integer isPrimaryAsInteger = contentValues.getAsInteger(Phone.IS_PRIMARY);
            final boolean isPrimary = (isPrimaryAsInteger != null ? (isPrimaryAsInteger > 0) : false);
            String phoneNumber = contentValues.getAsString(Phone.NUMBER);
            if (phoneNumber != null) {
                phoneNumber = phoneNumber.trim();
            }//  w  w  w  .  j a  v  a2  s . c om
            if (TextUtils.isEmpty(phoneNumber)) {
                continue;
            }
            int type = (typeAsObject != null ? typeAsObject : DEFAULT_PHONE_TYPE);
            if (type == Phone.TYPE_PAGER) {
                phoneLineExists = true;
                if (!phoneSet.contains(phoneNumber)) {
                    phoneSet.add(phoneNumber);
                    appendTelLine(type, label, phoneNumber, isPrimary);
                }
            } else {
                // The entry "may" have several phone numbers when the contact entry is
                // corrupted because of its original source.
                //
                // e.g. I encountered the entry like the following.
                // "111-222-3333 (Miami)\n444-555-6666 (Broward; 305-653-6796 (Miami); ..."
                // This kind of entry is not able to be inserted via Android devices, but
                // possible if the source of the data is already corrupted.
                List<String> phoneNumberList = splitIfSeveralPhoneNumbersExist(phoneNumber);
                if (phoneNumberList.isEmpty()) {
                    continue;
                }
                phoneLineExists = true;
                for (String actualPhoneNumber : phoneNumberList) {
                    if (!phoneSet.contains(actualPhoneNumber)) {
                        // final int format = VCardUtils.getPhoneNumberFormat(mVCardType);
                        //final String formattedPhoneNumber =
                        //        PhoneNumberUtils.formatNumber(actualPhoneNumber, format);
                        // final int format = VCardUtils.getPhoneNumberFormat(mVCardType);
                        final String formattedPhoneNumber = PhoneNumberUtils.formatNumber(actualPhoneNumber);
                        phoneSet.add(actualPhoneNumber);
                        appendTelLine(type, label, formattedPhoneNumber, isPrimary);
                    }
                }
            }
        }
    }

    if (!phoneLineExists && mIsDoCoMo) {
        appendTelLine(Phone.TYPE_HOME, "", "", false);
    }

    return this;
}