Example usage for android.content ContentValues get

List of usage examples for android.content ContentValues get

Introduction

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

Prototype

public Object get(String key) 

Source Link

Document

Gets a value.

Usage

From source file:com.andrew.apolloMod.helpers.AddIdCursorLoader.java

@Override
public Cursor loadInBackground() {

    Cursor mediaCursor = getContext().getContentResolver().query(mUri, mProjection, mSelection, mSelectionArgs,
            mSortOrder);/*from ww w .ja va  2s .  com*/
    //Get cursor filled with Audio Id's
    String[] projection = new String[] { BaseColumns._ID, AlbumColumns.ALBUM };
    Uri uri = Audio.Albums.EXTERNAL_CONTENT_URI;
    String sortOrder = Audio.Albums.DEFAULT_SORT_ORDER;
    Cursor albumCursor = getContext().getContentResolver().query(uri, projection, null, null, sortOrder);

    //Matrix cursor to hold final data to be returned to calling context
    MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID, MediaColumns.TITLE,
            AudioColumns.ARTIST, AudioColumns.ALBUM, AudioColumns.ALBUM_ID });
    //Map data from Audio Id cursor to the ALbumName Colum
    ContentQueryMap mQueryMap = new ContentQueryMap(albumCursor, AlbumColumns.ALBUM, false, null);

    Map<String, ContentValues> data = mQueryMap.getRows();
    if (mediaCursor != null) {
        while (mediaCursor.moveToNext()) {
            String id = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(BaseColumns._ID));
            String title = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(MediaColumns.TITLE));
            String artist = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(AudioColumns.ARTIST));
            String album = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(AudioColumns.ALBUM));

            ContentValues tData = data.get(album);
            String albumid = (String) tData.get(BaseColumns._ID);
            cursor.addRow(new String[] { id, title, artist, album, albumid });
        }
        mediaCursor.close();
    }

    if (cursor != null) {
        // Ensure the cursor window is filled
        registerContentObserver(cursor, mObserver);
    }
    return cursor;
}

From source file:org.droidparts.inner.converter.ArrayCollectionConverter.java

@Override
public <G1, G2> void putToContentValues(Class<Object> valueType, Class<G1> genericArg1, Class<G2> genericArg2,
        ContentValues cv, String key, Object val) throws Exception {
    Converter<G1> converter = ConverterRegistry.getConverter(genericArg1);
    if (converter.getDBColumnType() == BLOB) {
        byte[] bytes = PersistUtils.toBytes(val);
        cv.put(key, bytes);/*from w w w . ja va2s  . c  o m*/
    } else {
        ArrayList<G1> list = arrOrCollToList(valueType, genericArg1, val);
        ArrayList<Object> vals = new ArrayList<Object>();
        ContentValues tmpCV = new ContentValues();
        for (G1 obj : list) {
            converter.putToContentValues(genericArg1, null, null, tmpCV, "key", obj);
            vals.add(tmpCV.get("key"));
        }
        String strVal = Strings.join(vals, SEP);
        cv.put(key, strVal);
    }
}

From source file:com.udacity.movietimes.adapter.MovieDetailAdapter.java

public void updateFavoriteButton(final MovieViewHolder viewHolder, final Context context, final Cursor cursor) {
    // set the favorite button of the movie. First we check in the database if the favorite column
    // is Y or N. Based on that we switch the indicator as well as update the data in Movie DB.
    // Its basically act like a switch to update favorite column in the Movie Table
    Uri uri = MovieContract.MovieEntry.buildMovieWithMovieId(cursor.getLong(COL_ID));
    Cursor temp = context.getContentResolver().query(uri, null, null, null, null, null);
    temp.moveToFirst();/*from w w  w . java  2  s  .c  o  m*/
    final ContentValues values = new ContentValues();
    DatabaseUtils.cursorRowToContentValues(temp, values);

    Typeface fontFamily = Typeface.createFromAsset(context.getAssets(), "fonts/fontawesome.ttf");
    viewHolder.favorite.setTypeface(fontFamily);

    if (values.get(MovieContract.MovieEntry.COLUMN_FAVORITE).equals("N")) {
        viewHolder.favorite.setText("\uf196");
    } else {
        viewHolder.favorite.setText("\uf14a");
    }

    viewHolder.favorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String movieId = (String) values.get(MovieContract.MovieEntry.COLUMN_MOVIE_ID);
            if (values.get(MovieContract.MovieEntry.COLUMN_FAVORITE).equals("N")) {
                values.put(MovieContract.MovieEntry.COLUMN_FAVORITE, "Y");
                viewHolder.favorite.setText("\uf14a");

            } else {
                values.put(MovieContract.MovieEntry.COLUMN_FAVORITE, "N");
                viewHolder.favorite.setText("\uf196");

            }
            context.getContentResolver().update(MovieContract.MovieEntry.CONTENT_URI, values,
                    MovieContract.MovieEntry.COLUMN_MOVIE_ID + " = ? ", new String[] { movieId });

        }
    });

}

From source file:com.openerp.addons.messages.MessageSyncHelper.java

/**
 * Handle message response.//from  w  ww  . j a va  2s.c  o  m
 * 
 * @param db
 *            the db
 * @param response
 *            the response
 * @return the int
 */
private int handleMessageResponse(BaseDBHelper db, JSONObject response) {
    String[] columns = db.columnListToStringArray(db.getServerColumns());
    ContentValues values = new ContentValues();
    int newId = 0;

    try {
        for (String column : columns) {
            if (response.has(column)) {
                values.put(column, response.getString(column));
            }
        }

        if (values.get("subject").toString().equals("false")) {
            values.put("subject", response.getString("record_name"));
        }

        String author = "false";
        String email_from = "false";
        if (response.getJSONArray("author_id").getString(0).equals("0")) {
            email_from = response.getJSONArray("author_id").getString(1).toString();
        } else {
            author = response.getString("author_id");
        }
        values.put("author_id", author);
        values.put("email_from", email_from);

        String parent_id = "false";
        if (!response.getString("parent_id").equals("false")) {
            if (response.get("parent_id") instanceof JSONArray) {
                parent_id = response.getJSONArray("parent_id").getString(0);
            } else {
                parent_id = response.getString("parent_id");
            }
        }
        values.put("parent_id", parent_id);

        String starred = "false";
        if (response.has("is_favorite")) {
            if (response.getString("is_favorite").equals("true")) {
                starred = "true";
            }
        }
        values.put("starred", starred);
        if (!db.hasRecord(db, response.getInt("id"))) {
            // Sending Broadcast message for data set change.
            Intent intent = new Intent();
            intent.setAction(DataSetChangeReceiver.DATA_CHANGED);
            newId = db.create(db, values);
            intent.putExtra("id", String.valueOf(newId));
            intent.putExtra("parent_id", parent_id);
            mContext.sendBroadcast(intent);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return newId;
}

From source file:com.odoo.support.provider.OContentProvider.java

private HashMap<String, List<Integer>> getManyToManyRecords(ContentValues values) {
    HashMap<String, List<Integer>> ids = new HashMap<String, List<Integer>>();
    for (OColumn col : model.getRelationColumns()) {
        if (col.getRelationType() == RelationType.ManyToMany) {
            if (values.containsKey(col.getName())) {
                List<Integer> record_ids = new ArrayList<Integer>();
                try {
                    record_ids.addAll(/*from ww w  .ja va 2s . c  o m*/
                            JSONUtils.<Integer>toList(new JSONArray(values.get(col.getName()).toString())));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ids.put(col.getName(), record_ids);
                values.remove(col.getName());
            }
        }
    }
    return ids;
}

From source file:com.photowall.oauth.util.BaseHttpClient.java

/**
 * /* www  .j  a va  2s.c om*/
 * @param mContext
 */
private void setProxy(Context mContext) {
    try {
        ContentValues values = new ContentValues();
        Cursor cur = mContext.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"),
                null, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            if (cur.moveToFirst()) {
                int colCount = cur.getColumnCount();
                for (int i = 0; i < colCount; i++) {
                    values.put(cur.getColumnName(i), cur.getString(i));
                }
            }
            cur.close();
        }
        String proxyHost = (String) values.get("proxy");
        if (!TextUtils.isEmpty(proxyHost) && !isWiFiConnected(mContext)) {
            int prot = Integer.parseInt(String.valueOf(values.get("port")));
            delegate.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, prot),
                    new UsernamePasswordCredentials((String) values.get("user"),
                            (String) values.get("password")));
            HttpHost proxy = new HttpHost(proxyHost, prot);
            delegate.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w(TAG, "set proxy error+++++++++++++++++");
    }
}

From source file:com.openerp.addons.note.EditNoteFragment.java

public void updateNote(int row_id) {

    try {/*  w w w . j a v  a2  s. c  o  m*/
        JSONArray tagID = db.getSelectedTagId(selectedTags);
        long stage_id = Long.parseLong(stages.get(noteStages.getSelectedItem().toString()));
        ContentValues values = new ContentValues();
        JSONObject vals = new JSONObject();

        // If Pad Installed Over Server
        if (padAdded) {
            JSONArray url = new JSONArray();
            url.put(originalMemo);
            JSONObject obj = oe_obj.call_kw("pad.common", "pad_get_content", url);

            // HTMLHelper helper = new HTMLHelper();
            String link = HTMLHelper.htmlToString(obj.getString("result"));
            values.put("stage_id", stage_id);
            vals.put("stage_id", Integer.parseInt(values.get("stage_id").toString()));

            values.put("name", db.generateName(link));
            vals.put("name", values.get("name").toString());

            values.put("memo", obj.getString("result"));
            vals.put("memo", values.get("memo").toString());

            values.put("note_pad_url", originalMemo);
            vals.put("note_pad_url", values.get("note_pad_url").toString());
        } // If Pad Not Installed Over Server
        else {
            values.put("stage_id", stage_id);
            vals.put("stage_id", Integer.parseInt(values.get("stage_id").toString()));

            values.put("name", db.generateName(noteMemo.getText().toString()));
            vals.put("name", values.get("name").toString());

            values.put("memo", Html.toHtml(noteMemo.getText()));
            vals.put("memo", values.get("memo").toString());
        }

        JSONArray tag_ids = new JSONArray();
        tag_ids.put(6);
        tag_ids.put(false);
        JSONArray c_ids = new JSONArray(tagID.toString());
        tag_ids.put(c_ids);
        vals.put("tag_ids", new JSONArray("[" + tag_ids.toString() + "]"));

        // This will update Notes over Server And Local database
        db = new NoteDBHelper(scope.context());
        if (oe_obj.updateValues(db.getModelName(), vals, row_id)) {
            db.write(db, values, row_id, true);
            db.executeSQL("delete from note_note_note_tag_rel where note_note_id = ? and oea_name = ?",
                    new String[] { row_id + "", scope.User().getAndroidName() });
            for (int i = 0; i < tagID.length(); i++) {
                ContentValues rel_vals = new ContentValues();
                rel_vals.put("note_note_id", row_id);
                rel_vals.put("note_tag_id", tagID.getInt(i));
                rel_vals.put("oea_name", scope.User().getAndroidName());
                SQLiteDatabase insertDb = db.getWritableDatabase();
                insertDb.insert("note_note_note_tag_rel", null, rel_vals);
                insertDb.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.android.messaging.datamodel.BugleDatabaseOperations.java

@DoesNotRunOnMainThread
public static boolean updateRowIfExists(final DatabaseWrapper db, final String table, final String rowKey,
        final String rowId, final ContentValues values) {
    Assert.isNotMainThread();/*  www  .  j  a  v  a 2 s.com*/
    final StringBuilder sb = new StringBuilder();
    final ArrayList<String> whereValues = new ArrayList<String>(values.size() + 1);
    whereValues.add(rowId);

    for (final String key : values.keySet()) {
        if (sb.length() > 0) {
            sb.append(" OR ");
        }
        final Object value = values.get(key);
        sb.append(key);
        if (value != null) {
            sb.append(" IS NOT ?");
            whereValues.add(value.toString());
        } else {
            sb.append(" IS NOT NULL");
        }
    }

    final String whereClause = rowKey + "=?" + " AND (" + sb.toString() + ")";
    final String[] whereValuesArray = whereValues.toArray(new String[whereValues.size()]);
    final int count = db.update(table, values, whereClause, whereValuesArray);
    if (count > 1) {
        LogUtil.w(LogUtil.BUGLE_TAG, "Updated more than 1 row " + count + "; " + table + " for " + rowKey
                + " = " + rowId + " (deleted?)");
    }
    Assert.inRange(count, 0, 1);
    return (count >= 0);
}

From source file:org.mozilla.gecko.tests.BaseTest.java

public boolean CursorMatches(Cursor c, ContentValues cv) {
    for (int i = 0; i < c.getColumnCount(); i++) {
        String column = c.getColumnName(i);
        if (cv.containsKey(column)) {
            mAsserter.info("Comparing", "Column values for: " + column);
            Object value = cv.get(column);
            if (value == null) {
                if (!c.isNull(i)) {
                    return false;
                }/*from   w  ww.  j a v a  2 s.  c  o  m*/
            } else {
                if (c.isNull(i) || !value.toString().equals(c.getString(i))) {
                    return false;
                }
            }
        }
    }
    return true;
}

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

@Override
public synchronized Uri insert(@NonNull Uri uri, ContentValues initialValues) {
    possiblyWaitForContentProviderDebugger();

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

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }/*from   ww  w.ja  v a  2 s  .com*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLoggerIf log = WebLogger.getLogger(appName);

    HashMap<String, Object> values = new HashMap<String, Object>();
    if (initialValues != null) {
        for (String key : initialValues.keySet()) {
            values.put(key, initialValues.get(key));
        }
    }

    // force a scan from disk
    values.remove(FormsColumns.DATE);
    values.remove(FormsColumns.JSON_MD5_HASH);
    FormSpec formSpec = patchUpValues(appName, values);

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.TABLE_ID, FormsColumns.FORM_ID };
    String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?";
    String[] selectionArgs = { formSpec.tableId, formSpec.formId };
    Cursor c = null;

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null, null);
            if (c == null) {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- unable to query for existing records. tableId="
                                + formSpec.tableId + " formId=" + formSpec.formId);
            }
            c.moveToFirst();
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri + " -- row already exists for  tableId="
                        + formSpec.tableId + " formId=" + formSpec.formId);
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        try {
            long rowId = db.insertOrThrow(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            // and notify listeners of the new row...
            Uri formUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                    (String) values.get(FormsColumns.FORM_ID));
            getContext().getContentResolver().notifyChange(formUri, null);
            Uri idUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                    Long.toString(rowId));
            getContext().getContentResolver().notifyChange(idUri, null);

            return formUri;
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } catch (SQLException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException("FAILED Insert into " + uri + " -- insert of 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(appName,
                            dbHandleName);
                }
            }
        }
    }
}