Example usage for android.content ContentValues ContentValues

List of usage examples for android.content ContentValues ContentValues

Introduction

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

Prototype

public ContentValues() 

Source Link

Document

Creates an empty set of values using the default initial size

Usage

From source file:com.seneca.android.senfitbeta.DbHelper.java

public void insertMuscles(int id, String name) {
    Log.d("INSERT DB", "Inserting muscles...");

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(RIP_ID, id);/*from   w  ww  .  ja v  a 2s  .co  m*/
    values.put(RIP_NAME, name);
    long info = db.insert(RIP_TABLE, null, values);

}

From source file:com.google.android.apps.iosched.ui.VendorDetailActivity.java

/** Handle toggling of starred checkbox. */
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    final ContentValues values = new ContentValues();
    values.put(Vendors.STARRED, isChecked ? 1 : 0);
    mHandler.startUpdate(mVendorUri, values);
}

From source file:com.morphoss.acal.service.UpdateTimezones.java

private void refreshTimezoneData() {
    try {/*ww  w  .  j a v a 2  s .c  om*/
        HashMap<String, Long> currentZones = new HashMap<String, Long>();
        HashMap<String, Long> updatedZones = new HashMap<String, Long>();
        HashMap<String, Long> insertedZones = new HashMap<String, Long>();
        Cursor allZones = cr.query(Timezones.CONTENT_URI,
                new String[] { Timezones.TZID, Timezones.LAST_MODIFIED }, null, null, null);
        Long maxModified = 0L;
        for (allZones.moveToFirst(); !allZones.isAfterLast(); allZones.moveToNext()) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found existing zone of '" + allZones.getString(0)
                        + "' modified: " + AcalDateTime.fromMillis(allZones.getLong(1) * 1000L).toString());
            currentZones.put(allZones.getString(0), allZones.getLong(1));
            if (allZones.getLong(1) > maxModified)
                maxModified = allZones.getLong(1);
        }
        AcalDateTime mostRecentChange = AcalDateTime.getUTCInstance().setEpoch(maxModified);
        Log.println(Constants.LOGI, TAG, "Found " + allZones.getCount()
                + " existing timezones, most recent change on " + mostRecentChange.toString());
        if (allZones.getCount() > 350 && mostRecentChange.after(AcalDateTime.getUTCInstance().addDays(-30))) {
            Log.println(Constants.LOGI, TAG, "Skipping update - our database is pretty recent");
            return;
        }

        requestor.interpretUriString(tzUrl("list", null));
        JSONObject root = requestor.doJsonRequest("GET", null, null, null);
        if (requestor.wasRedirected()) {
            Uri tzUri = Uri.parse(requestor.fullUrl());
            String redirectedUrl = tzUri.getScheme() + "://" + tzUri.getAuthority() + tzUri.getPath();
            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Redirected to Timezone Server at " + redirectedUrl);
            tzServerBaseUrl = redirectedUrl;
            AcalApplication.setPreferenceString(PrefNames.tzServerBaseUrl, redirectedUrl);
        }
        if (requestor.getStatusCode() >= 399) {
            Log.println(Constants.LOGI, TAG, "Bad response " + requestor.getStatusCode()
                    + " from Timezone Server at " + tzUrl("list", null));
        }
        if (root == null) {
            Log.println(Constants.LOGI, TAG, "No JSON from GET " + tzUrl("list", null));
            return;
        }

        String tzid;
        String tzData = "";
        long lastModified;
        StringBuilder localNames;
        StringBuilder aliases;
        ContentValues zoneValues = new ContentValues();

        String tzDateStamp = root.getString("dtstamp");
        JSONArray tzArray = root.getJSONArray("timezones");
        for (int i = 0; i < tzArray.length(); i++) {
            JSONObject zoneNode = tzArray.getJSONObject(i);
            tzid = zoneNode.getString("tzid");
            if (updatedZones.containsKey(tzid) || insertedZones.containsKey(tzid))
                continue;

            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Working on " + tzid);

            lastModified = AcalDateTime.fromString(zoneNode.getString("last-modified")).getEpoch();
            if (currentZones.containsKey(tzid) && currentZones.get(tzid) <= lastModified) {
                currentZones.remove(tzid);
                continue;
            }

            tzData = getTimeZone(tzid);
            if (tzData == null)
                continue;

            localNames = new StringBuilder();
            try {
                JSONArray nameNodes = zoneNode.getJSONArray("local_names");
                for (int j = 0; j < nameNodes.length(); j++) {
                    if (localNames.length() > 0)
                        localNames.append("\n");
                    localNames.append(nameNodes.getJSONObject(j).getString("lang")).append('~')
                            .append(nameNodes.getJSONObject(j).getString("lname"));
                }
            } catch (JSONException je) {
            }

            aliases = new StringBuilder();
            try {
                JSONArray aliasNodes = zoneNode.getJSONArray("aliases");
                for (int j = 0; j < aliasNodes.length(); j++) {
                    if (aliases.length() > 0)
                        aliases.append("\n");
                    aliases.append(aliasNodes.getString(j));
                }
            } catch (JSONException je) {
            }

            zoneValues.put(Timezones.TZID, tzid);
            zoneValues.put(Timezones.ZONE_DATA, tzData);
            zoneValues.put(Timezones.LAST_MODIFIED, lastModified);
            zoneValues.put(Timezones.TZ_NAMES, localNames.toString());
            zoneValues.put(Timezones.TZID_ALIASES, aliases.toString());

            Uri tzUri = Uri.withAppendedPath(Timezones.CONTENT_URI,
                    "tzid/" + StaticHelpers.urlescape(tzid, false));

            if (currentZones.containsKey(tzid)) {
                if (cr.update(tzUri, zoneValues, null, null) != 1) {
                    Log.e(TAG, "Failed update for TZID '" + tzid + "'");
                }
                updatedZones.put(tzid, currentZones.get(tzid));
                currentZones.remove(tzid);
            } else {
                if (cr.insert(tzUri, zoneValues) == null)
                    Log.e(TAG, "Failed insert for TZID '" + tzid + "'");
                insertedZones.put(tzid, currentZones.get(tzid));
            }

            if (context.workWaiting()) {
                Log.println(Constants.LOGI, TAG, "Something is waiting - deferring timezone sync until later.");
                deferMe = true;
                break;
            }
            // Let other stuff have a chance
            Thread.sleep(350);
        }
        int removed = 0;

        if (currentZones.size() > 0) {
            StringBuilder s = new StringBuilder();
            for (String tz : currentZones.keySet()) {
                if (s.length() > 0)
                    s.append(',');
                s.append("'").append(tz).append("'");
            }
            removed = cr.delete(Timezones.CONTENT_URI, Timezones.TZID + " IN (" + s + ")", null);
        }

        Log.println(Constants.LOGI, TAG, "Updated data for " + updatedZones.size() + " zones, added data for "
                + insertedZones.size() + " new zones, removed data for " + removed);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:com.dycody.android.idealnote.async.upgrade.UpgradeProcessor.java

/**
 * Ensures that no duplicates will be found during the creation-to-id transition
 *//*from w ww  . j ava  2s  . c  om*/
private void onUpgradeTo501() {
    List<Long> creations = new ArrayList<>();
    for (Note note : DbHelper.getInstance().getAllNotes(false)) {
        if (creations.contains(note.getCreation())) {

            ContentValues values = new ContentValues();
            values.put(DbHelper.KEY_CREATION, note.getCreation() + (long) (Math.random() * 999));
            DbHelper.getInstance().getDatabase().update(DbHelper.TABLE_NOTES, values,
                    DbHelper.KEY_TITLE + " = ? AND " + DbHelper.KEY_CREATION + " = ? AND "
                            + DbHelper.KEY_CONTENT + " = ?",
                    new String[] { note.getTitle(), String.valueOf(note.getCreation()), note.getContent() });
        }
        creations.add(note.getCreation());
    }
}

From source file:android.provider.Checkin.java

/**
 * Helper function to update statistics in the database.
 * Note that multiple updates to the same tag will be combined.
 *
 * @param tag identifying what is being observed
 * @param count of occurrences//from   w  w w . j a  v a 2 s.c  om
 * @param sum of some value over these occurrences
 * @return URI of the statistic that was returned
 */
static public Uri updateStats(ContentResolver resolver, Stats.Tag tag, int count, double sum) {
    try {
        ContentValues values = new ContentValues();
        values.put(Stats.TAG, tag.toString());
        if (count != 0)
            values.put(Stats.COUNT, count);
        if (sum != 0.0)
            values.put(Stats.SUM, sum);
        return resolver.insert(Stats.CONTENT_URI, values);
    } catch (SQLException e) {
        Log.e(TAG, "Can't update stat: " + tag, e); // Database errors are not fatal.
        return null;
    }
}

From source file:com.github.longkai.zhihu.util.Utils.java

/**
 * ???ContentValues?/*from   w  w  w .j a  v  a2s  .  c o  m*/
 * @param jsonArray data
 * @return itemstopicscontent values map
 */
public static Map<String, ContentValues[]> process(JSONArray jsonArray) {
    ContentValues[] items = new ContentValues[jsonArray.length()];
    List<ContentValues> topics = new ArrayList<ContentValues>();
    ContentValues item;
    ContentValues topic;
    // ??
    JSONArray array;
    JSONArray user;
    JSONArray question;
    JSONArray _topics;
    JSONArray _topic;
    // ??id??(?
    // ??= =)123,321,456,
    StringBuilder topicIds = new StringBuilder();
    // ??item???
    long millis = System.currentTimeMillis();

    for (int i = 0; i < items.length; i++) {
        array = jsonArray.optJSONArray(i);
        item = new ContentValues();

        item.put(BaseColumns._ID, millis--);

        // 
        item.put(STATUS, array.optString(1));
        item.put(ANSWER, array.optString(2));
        item.put(VOTE, array.optInt(3));
        item.put(LAST_ALTER_DATE, array.optLong(4) * 1000);
        item.put(ANSWER_ID, array.optLong(5));

        // 
        user = array.optJSONArray(6);
        if (user != null) {
            item.put(NICK, user.optString(0));
            item.put(UID, user.optString(1));
            item.put(AVATAR, user.optString(2));
        }

        // 
        question = array.optJSONArray(7);
        if (question != null) {
            item.put(TITLE, question.optString(1, null));
            item.put(DESCRIPTION, question.optString(2));
            item.put(QUESTION_ID, question.optLong(3));
            item.put(STARRED, question.optLong(5));
            item.put(VIEWED, question.optLong(6));
        }

        // ?
        topicIds.setLength(0);
        if (!question.isNull(7)) {
            _topics = question.optJSONArray(7);
            for (int j = 0; j < _topics.length(); j++) {
                _topic = _topics.optJSONArray(j);
                topic = new ContentValues(4);
                topic.put(TOPIC_NAME, _topic.optString(1, null));
                topic.put(TOPIC_DESCRIPTION, _topic.optString(2));
                topic.put(TOPIC_AVATAR, _topic.optString(3));
                topic.put(TOPIC_ID, _topic.optLong(4));
                // todo ?????replace?
                // ?????????
                topics.add(topic);

                // ?item?
                topicIds.append(_topic.optLong(4)).append(",");
            }
        }
        item.put(TOPICS, topicIds.toString());

        // ?json
        item.put(VOTERS, array.isNull(8) ? null : array.optJSONArray(8).toString());

        items[i] = item;
    }

    Map<String, ContentValues[]> map = new HashMap<String, ContentValues[]>(2);
    map.put(ITEMS, items);
    map.put(TOPICS, topics.toArray(new ContentValues[0]));
    return map;
}

From source file:com.example.android.touroflondon.data.TourDbHelper.java

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add it to the POI table.
 *
 * @param data/*w  w  w .j a v a 2  s  .c  om*/
 */
public void loadPois(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // empty the POI table to remove all existing data
    db.delete(TourContract.PoiEntry.TABLE_NAME, null, null);

    // need to complete transaction first to clear data
    db.close();

    // begin the insert transaction
    db = this.getWritableDatabase();
    db.beginTransaction();

    // Loop over each point of interest in array
    for (int i = 0; i < DataStore.getAllCoupons().size(); i++) {
        Coupon coupon = DataStore.getAllCoupons().get(i);
        //Extract POI properties
        final String storeName = coupon.getStoreName();
        String details = coupon.getTitle();
        details = details.replace("<h1>", "").replace("</h1>", "");

        final Double lat = coupon.getLatitude();
        final Double lng = coupon.getLongitude();
        /* 
        /final String type = poi.getString("type");
         final String description = poi.getString("description");
         final String pictureUrl = poi.getString("pictureUrl");
         final String pictureAttr = poi.getString("pictureAttr");
                
         // Location
         JSONObject location = poi.getJSONObject("location");
         final double lat = location.getDouble("lat");
         final double lng = location.getDouble("lng");
         */
        // Create content values object for insert
        ContentValues cv = new ContentValues();
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TITLE, storeName);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, "LANDMARK");
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, details);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);

        // Insert data
        db.insert(TourContract.PoiEntry.TABLE_NAME, null, cv);
    }

    // All insert statement have been submitted, mark transaction as successful
    db.setTransactionSuccessful();

    if (db != null) {
        db.endTransaction();
    }

}

From source file:net.peterkuterna.android.apps.devoxxsched.util.SyncUtils.java

public static void updateLocalMd5(ContentResolver resolver, String url, String md5) {
    final String syncId = Sync.generateSyncId(url);
    final ContentValues contentValues = new ContentValues();
    Log.d("SyncUtils", "syncId = " + syncId);
    Log.d("SyncUtils", "url = " + url);
    Log.d("SyncUtils", "md5 = " + md5);
    contentValues.put(Sync.URI_ID, syncId);
    contentValues.put(Sync.URI, url);
    contentValues.put(Sync.MD5, md5);/*from  w  ww  . j  av a  2 s.  c o m*/
    resolver.insert(Sync.CONTENT_URI, contentValues);
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

public void addHistoryItem(Result result, ResultHandler handler, String data) {
    // Do not save this item to the history if the preference is turned off,
    // or the contents are
    // considered secure.
    if (!activity.getIntent().getBooleanExtra(Intents.Scan.SAVE_HISTORY, true) || handler.areContentsSecure()) {
        return;/*from  www  .  j av a2  s. c  o m*/
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    if (!prefs.getBoolean(PreferencesActivity.KEY_REMEMBER_DUPLICATES, false)) {
        deletePrevious(result.getText());
    }

    ContentValues values = new ContentValues();
    values.put(DBHelper.TEXT_COL, result.getText());
    values.put(DBHelper.FORMAT_COL, result.getBarcodeFormat().toString());
    values.put(DBHelper.DISPLAY_COL, handler.getDisplayContents().toString());
    values.put(DBHelper.TIMESTAMP_COL, data.toString());

    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;
    try {
        db = helper.getWritableDatabase();
        // Insert the new entry into the DB.
        db.insert(DBHelper.TABLE_NAME, null, values);
    } finally {
        close(null, db);
    }
}

From source file:grytsenko.coworkers.web.Employee.java

/**
 * Obtains data about mobile phone number for {@link ContentResolver}.
 * /* ww  w  .jav a2 s  .  c o  m*/
 * @return the set of values.
 */
public ContentValues getMobile() {
    ContentValues values = new ContentValues();
    values.put(Phone.NUMBER, mobile);
    values.put(Phone.TYPE, Phone.TYPE_MOBILE);
    return values;
}