Example usage for android.content ContentValues putNull

List of usage examples for android.content ContentValues putNull

Introduction

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

Prototype

public void putNull(String key) 

Source Link

Document

Adds a null value to the set.

Usage

From source file:nl.privacybarometer.privacyvandaag.activity.EditFeedActivity.java

@Override
protected void onDestroy() {
    if (getIntent().getAction().equals(Intent.ACTION_EDIT)) {
        String url = mUrlEditText.getText().toString();
        ContentResolver cr = getContentResolver();

        Cursor cursor = null;// w w w . ja v  a2  s  .  co  m
        try {
            cursor = getContentResolver().query(FeedColumns.CONTENT_URI, FeedColumns.PROJECTION_ID,
                    FeedColumns.URL + Constants.DB_ARG, new String[] { url }, null);

            if (cursor != null && cursor.moveToFirst()
                    && !getIntent().getData().getLastPathSegment().equals(cursor.getString(0))) {
                Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Toast.LENGTH_LONG).show();
            } else {
                ContentValues values = new ContentValues();

                if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) {
                    url = Constants.HTTP_SCHEME + url;
                }
                values.put(FeedColumns.URL, url);

                String name = mNameEditText.getText().toString();
                String cookieName = mCookieNameEditText.getText().toString();
                String cookieValue = mCookieValueEditText.getText().toString();

                values.put(FeedColumns.NAME, name.trim().length() > 0 ? name : null);
                values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
                values.put(FeedColumns.COOKIE_NAME, cookieName.trim().length() > 0 ? cookieName : "");
                values.put(FeedColumns.COOKIE_VALUE, cookieValue.trim().length() > 0 ? cookieValue : "");
                final TypedArray selectedValues = getResources()
                        .obtainTypedArray(R.array.settings_keep_time_values);
                values.put(FeedColumns.KEEP_TIME,
                        selectedValues.getInt(mKeepTime.getSelectedItemPosition(), 0));
                values.put(FeedColumns.FETCH_MODE, 0);
                values.putNull(FeedColumns.ERROR);

                cr.update(getIntent().getData(), values, null, null);
            }
        } catch (Exception ignored) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    super.onDestroy();
}

From source file:org.kontalk.sync.Syncer.java

/**
 * The actual sync procedure./*from   www.  ja v a2s .  co  m*/
 * This one uses the slowest method ever: it first checks for every phone
 * number in all contacts and it sends them to the server. Once a response
 * is received, it deletes all the raw contacts created by us and then
 * recreates only the ones the server has found a match for.
 */
public void performSync(Context context, Account account, String authority, ContentProviderClient provider,
        ContentProviderClient usersProvider, SyncResult syncResult) throws OperationCanceledException {

    final Map<String, RawPhoneNumberEntry> lookupNumbers = new HashMap<>();
    final List<String> jidList = new ArrayList<>();

    // resync users database
    Log.v(TAG, "resyncing users database");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // update users database
    Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").build();
    try {
        int count = usersProvider.update(uri, new ContentValues(), null, null);
        Log.d(TAG, "users database resynced (" + count + ")");
    } catch (Exception e) {
        Log.e(TAG, "error resyncing users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    // query all contacts
    Cursor cursor;
    try {
        cursor = usersProvider.query(Users.CONTENT_URI_OFFLINE,
                new String[] { Users.JID, Users.NUMBER, Users.LOOKUP_KEY }, null, null, null);
    } catch (Exception e) {
        Log.e(TAG, "error querying users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    while (cursor.moveToNext()) {
        if (mCanceled) {
            cursor.close();
            throw new OperationCanceledException();
        }

        String jid = cursor.getString(0);
        String number = cursor.getString(1);
        String lookupKey = cursor.getString(2);

        // avoid to send duplicates to the server
        if (lookupNumbers.put(XmppStringUtils.parseLocalpart(jid),
                new RawPhoneNumberEntry(lookupKey, number, jid)) == null)
            jidList.add(jid);
    }
    cursor.close();

    if (mCanceled)
        throw new OperationCanceledException();

    // empty contacts :-|
    if (jidList.size() == 0) {
        // delete all Kontalk raw contacts
        try {
            syncResult.stats.numDeletes += deleteAll(account, provider);
        } catch (Exception e) {
            Log.e(TAG, "contact delete error", e);
            syncResult.databaseError = true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            try {
                syncResult.stats.numDeletes += deleteProfile(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "profile delete error", e);
                syncResult.databaseError = true;
            }
        }

        commit(usersProvider, syncResult);
    }

    else {
        final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext);

        // register presence broadcast receiver
        PresenceBroadcastReceiver receiver = new PresenceBroadcastReceiver(jidList, this);
        IntentFilter f = new IntentFilter();
        f.addAction(MessageCenterService.ACTION_PRESENCE);
        f.addAction(MessageCenterService.ACTION_ROSTER_MATCH);
        f.addAction(MessageCenterService.ACTION_PUBLICKEY);
        f.addAction(MessageCenterService.ACTION_BLOCKLIST);
        f.addAction(MessageCenterService.ACTION_LAST_ACTIVITY);
        f.addAction(MessageCenterService.ACTION_CONNECTED);
        lbm.registerReceiver(receiver, f);

        // request current connection status
        MessageCenterService.requestConnectionStatus(mContext);

        // wait for the service to complete its job
        synchronized (this) {
            // wait for connection
            try {
                wait(MAX_WAIT_TIME);
            } catch (InterruptedException e) {
                // simulate canceled operation
                mCanceled = true;
            }
        }

        lbm.unregisterReceiver(receiver);

        // last chance to quit
        if (mCanceled)
            throw new OperationCanceledException();

        List<PresenceItem> res = receiver.getResponse();
        if (res != null) {
            ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
            // TODO operations.size() could be used instead (?)
            int op = 0;

            // this is the time - delete all Kontalk raw contacts
            try {
                syncResult.stats.numDeletes += deleteAll(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "contact delete error", e);
                syncResult.databaseError = true;
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                try {
                    syncResult.stats.numDeletes += deleteProfile(account, provider);
                } catch (Exception e) {
                    Log.e(TAG, "profile delete error", e);
                    syncResult.databaseError = true;
                }
            }

            ContentValues registeredValues = new ContentValues();
            registeredValues.put(Users.REGISTERED, 1);
            for (int i = 0; i < res.size(); i++) {
                PresenceItem entry = res.get(i);
                if (entry.discarded)
                    continue;

                final RawPhoneNumberEntry data = lookupNumbers.get(XmppStringUtils.parseLocalpart(entry.from));
                if (data != null && data.lookupKey != null) {
                    // add contact
                    addContact(account, getDisplayName(provider, data.lookupKey, data.number), data.number,
                            data.jid, operations, op++);
                } else {
                    syncResult.stats.numSkippedEntries++;
                }

                // update fields
                try {
                    String status = entry.status;

                    if (!TextUtils.isEmpty(status))
                        registeredValues.put(Users.STATUS, status);
                    else
                        registeredValues.putNull(Users.STATUS);

                    if (entry.timestamp >= 0)
                        registeredValues.put(Users.LAST_SEEN, entry.timestamp);
                    else
                        registeredValues.putNull(Users.LAST_SEEN);

                    if (entry.publicKey != null) {
                        try {
                            PGPPublicKey pubKey = PGP.getMasterKey(entry.publicKey);
                            // trust our own key blindly
                            int trustLevel = Authenticator.isSelfJID(mContext, entry.from)
                                    ? MyUsers.Keys.TRUST_VERIFIED
                                    : -1;
                            // update keys table immediately
                            Keyring.setKey(mContext, entry.from, entry.publicKey, trustLevel);

                            // no data from system contacts, use name from public key
                            if (data == null) {
                                PGPUserID uid = PGP.parseUserId(pubKey,
                                        XmppStringUtils.parseDomain(entry.from));
                                if (uid != null) {
                                    registeredValues.put(Users.DISPLAY_NAME, uid.getName());
                                }
                            }
                        } catch (Exception e) {
                            Log.w(TAG, "unable to parse public key", e);
                        }
                    } else {
                        // use roster name if no contact data available
                        if (data == null && entry.rosterName != null) {
                            registeredValues.put(Users.DISPLAY_NAME, entry.rosterName);
                        }
                    }

                    // blocked status
                    registeredValues.put(Users.BLOCKED, entry.blocked);
                    // user JID as reported by the server
                    registeredValues.put(Users.JID, entry.from);

                    /*
                     * Since UsersProvider.resync inserted the user row
                     * using our server name, it might have changed because
                     * of what the server reported. We already put into the
                     * values the new JID, but we need to use the old one
                     * in the where condition so we will have a match.
                     */
                    String origJid;
                    if (data != null)
                        origJid = XMPPUtils.createLocalJID(mContext,
                                XmppStringUtils.parseLocalpart(entry.from));
                    else
                        origJid = entry.from;
                    usersProvider.update(Users.CONTENT_URI_OFFLINE, registeredValues, Users.JID + " = ?",
                            new String[] { origJid });

                    // clear data
                    registeredValues.remove(Users.DISPLAY_NAME);

                    // if this is our own contact, trust our own key later
                    if (Authenticator.isSelfJID(mContext, entry.from)) {
                        // register our profile while we're at it
                        if (data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                            // add contact
                            addProfile(account, Authenticator.getDefaultDisplayName(mContext), data.number,
                                    data.jid, operations, op++);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "error updating users database", e);
                    // we shall continue here...
                }
            }

            try {
                if (operations.size() > 0)
                    provider.applyBatch(operations);
                syncResult.stats.numInserts += op;
                syncResult.stats.numEntries += op;
            } catch (Exception e) {
                Log.w(TAG, "contact write error", e);
                syncResult.stats.numSkippedEntries += op;
                /*
                 * We do not consider system contacts failure a fatal error.
                 * This is actually a workaround for systems with disabled permissions or
                 * exotic firmwares. It can also protect against security 3rd party apps or
                 * non-Android platforms, such as Jolla/Alien Dalvik.
                 */
            }

            commit(usersProvider, syncResult);
        }

        // timeout or error
        else {
            Log.w(TAG, "connection timeout - aborting sync");

            syncResult.stats.numIoExceptions++;
        }
    }
}

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

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);

    if (oldVersion <= 23) {
        Log.w(TAG, "Schema too old to migrate, dropping all.");
        dropAll(db);//  ww  w  .  jav  a  2s .c o  m
        onCreate(db);
        return;
    }

    if (oldVersion <= 24) {
        Log.w(TAG, "Adding columns 'presence' and 'status' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.STATUS + " TEXT");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PRESENCE + " INTEGER DEFAULT "
                + Presence.AVAILABLE);
    }

    if (oldVersion <= 25) {
        Log.w(TAG, "Adding columns 'presence' and 'status' to contact table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.FEED_NAME + " TEXT");
    }

    if (oldVersion <= 26) {
        Log.w(TAG, "Adding column 'picture' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PICTURE + " BLOB");
    }

    if (oldVersion <= 27) {
        Log.w(TAG, "Adding column 'last_presence_time' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_PRESENCE_TIME
                + " INTEGER DEFAULT 0");
    }

    if (oldVersion <= 28) {
        Log.w(TAG, "Adding column 'picture' to my_info table.");
        db.execSQL("ALTER TABLE " + MyInfo.TABLE + " ADD COLUMN " + MyInfo.PICTURE + " BLOB");
    }
    if (oldVersion <= 29) {
        Log.w(TAG, "Adding column 'version' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.VERSION + " INTEGER DEFAULT -1");
    }
    if (oldVersion <= 30) {
        Log.w(TAG, "Adding column 'E' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.ENCODED + " BLOB");
        createIndex(db, "INDEX", "objects_by_encoded", DbObject.TABLE, DbObject.ENCODED);
    }
    if (oldVersion <= 31) {
        Log.w(TAG, "Adding column 'child_feed' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.CHILD_FEED_NAME + " TEXT");
        createIndex(db, "INDEX", "child_feeds", DbObject.TABLE, DbObject.CHILD_FEED_NAME);
    }
    if (oldVersion <= 32) {
        // Bug fix.
        Log.w(TAG, "Updating app state objects.");
        db.execSQL("UPDATE " + DbObject.TABLE + " SET " + DbObject.CHILD_FEED_NAME + " = NULL WHERE "
                + DbObject.CHILD_FEED_NAME + " = " + DbObject.FEED_NAME);
    }
    if (oldVersion <= 33) {
        Log.w(TAG, "Adding column 'nearby' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.NEARBY + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 34) {
        Log.w(TAG, "Adding column 'secret' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.SHARED_SECRET + " BLOB");

    }
    if (oldVersion <= 35) {
        Log.w(TAG, "Adding column 'last_updated' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.LAST_UPDATED + " INTEGER");
    }
    if (oldVersion <= 36) {
        // Can't easily drop columns, but 'update_id' and 'is_child_feed' are dead columns.

        Log.w(TAG, "Adding column 'parent_feed_id' to group table.");
        db.execSQL(
                "ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.PARENT_FEED_ID + " INTEGER DEFAULT -1");

        Log.w(TAG, "Adding column 'last_object_id' to group table.");
        db.execSQL(
                "ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.LAST_OBJECT_ID + " INTEGER DEFAULT -1");
    }
    if (oldVersion <= 37) {
        // Can't easily drop columns, but 'update_id' and 'is_child_feed' are dead columns.

        Log.w(TAG, "Adding column 'num_unread' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.NUM_UNREAD + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 38) {
        Log.w(TAG, "Adding column 'raw' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.RAW + " BLOB");
    }
    // sadly, we have to do this again because incoming voice obj's were not being split!
    if (oldVersion <= 50) {
        Log.w(TAG, "Converting voice and picture objs to raw.");

        Log.w(TAG, "Converting objs to raw.");
        Cursor c = db.query(DbObject.TABLE, new String[] { DbObject._ID },
                DbObject.TYPE + " = ? AND " + DbObject.RAW + " IS NULL", new String[] { PictureObj.TYPE }, null,
                null, null);
        ArrayList<Long> ids = new ArrayList<Long>();
        if (c.moveToFirst())
            do {
                ids.add(c.getLong(0));
            } while (c.moveToNext());
        c.close();
        DbEntryHandler dbh = DbObjects.forType(PictureObj.TYPE);
        for (Long id : ids) {
            c = db.query(DbObject.TABLE, new String[] { DbObject.JSON, DbObject.RAW }, DbObject._ID + " = ? ",
                    new String[] { String.valueOf(id.longValue()) }, null, null, null);
            if (c.moveToFirst())
                try {
                    String json = c.getString(0);
                    byte[] raw = c.getBlob(1);
                    c.close();
                    if (raw == null) {
                        Pair<JSONObject, byte[]> p = dbh.splitRaw(new JSONObject(json));
                        if (p != null) {
                            json = p.first.toString();
                            raw = p.second;
                            updateJsonAndRaw(db, id, json, raw);
                        }
                    }
                } catch (JSONException e) {
                }
            c.close();
        }
        c = db.query(DbObject.TABLE, new String[] { DbObject._ID },
                DbObject.TYPE + " = ? AND " + DbObject.RAW + " IS NULL", new String[] { VoiceObj.TYPE }, null,
                null, null);
        ids = new ArrayList<Long>();
        if (c.moveToFirst())
            do {
                ids.add(c.getLong(0));
            } while (c.moveToNext());
        c.close();
        dbh = DbObjects.forType(VoiceObj.TYPE);
        for (Long id : ids) {
            c = db.query(DbObject.TABLE, new String[] { DbObject.JSON, DbObject.RAW }, DbObject._ID + " = ? ",
                    new String[] { String.valueOf(id.longValue()) }, null, null, null);
            if (c.moveToFirst())
                try {
                    String json = c.getString(0);
                    byte[] raw = c.getBlob(1);
                    c.close();
                    if (raw == null) {
                        Pair<JSONObject, byte[]> p = dbh.splitRaw(new JSONObject(json));
                        if (p != null) {
                            json = p.first.toString();
                            raw = p.second;
                            updateJsonAndRaw(db, id, json, raw);
                        }
                    }
                } catch (JSONException e) {
                }
            c.close();
        }
    }
    if (oldVersion <= 40) {
        Log.w(TAG, "Adding column 'E' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.HASH + " INTEGER");
        createIndex(db, "INDEX", "objects_by_hash", DbObject.TABLE, DbObject.HASH);
        db.execSQL("DROP INDEX objects_by_encoded");
        db.delete(DbObject.TABLE, DbObject.TYPE + " = ?", new String[] { "profile" });
        db.delete(DbObject.TABLE, DbObject.TYPE + " = ?", new String[] { "profilepicture" });
        ContentValues cv = new ContentValues();
        cv.putNull(DbObject.ENCODED);
        db.update(DbObject.TABLE, cv, null, null);
    }
    if (oldVersion <= 41) {
        db.execSQL("DROP INDEX objects_by_sequence_id");
        db.execSQL("CREATE INDEX objects_by_sequence_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
                + DbObject.FEED_NAME + ", " + DbObject.SEQUENCE_ID + ")");
    }
    //secret to life, etc
    if (oldVersion <= 42) {
        db.execSQL("DROP INDEX objects_by_creator_id");
        db.execSQL("CREATE INDEX objects_by_creator_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
                + DbObject.SENT + ")");
    }

    if (oldVersion <= 44) {
        // oops.
        db.execSQL("DROP TABLE IF EXISTS " + DbRelation.TABLE);
        createRelationBaseTable(db);
    }
    if (oldVersion <= 45) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_OBJECT_ID + " INTEGER");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_UPDATED + " INTEGER");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.NUM_UNREAD + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 46) {
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.DELETED + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 47) {
        addRelationIndexes(db);
    }
    if (oldVersion <= 44) {
        createUserAttributesTable(db);
    }

    if (oldVersion <= 49) {
        if (oldVersion > 44) {
            db.execSQL("ALTER TABLE " + DbRelation.TABLE + " ADD COLUMN " + DbRelation.RELATION_TYPE + " TEXT");
            createIndex(db, "INDEX", "relations_by_type", DbRelation.TABLE, DbRelation.RELATION_TYPE);
        }
        db.execSQL("UPDATE " + DbRelation.TABLE + " SET " + DbRelation.RELATION_TYPE + " = 'parent'");
    }
    if (oldVersion <= 52) {
        Log.w(TAG, "Adding column 'about' to my_info table.");
        try {
            db.execSQL("ALTER TABLE " + MyInfo.TABLE + " ADD COLUMN " + MyInfo.ABOUT + " TEXT DEFAULT ''");
        } catch (Exception e) {
            // because of bad update, we just ignore the duplicate column error
        }
    }
    if (oldVersion <= 53) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.HIDDEN + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 55) {
        db.execSQL("ALTER TABLE " + DbObj.TABLE + " ADD COLUMN " + DbObj.COL_KEY_INT + " INTEGER");
    }
    if (oldVersion <= 56) {
        db.execSQL("DROP INDEX attrs_by_contact_id");
        createIndex(db, "INDEX", "attrs_by_contact_id", DbContactAttributes.TABLE,
                DbContactAttributes.CONTACT_ID);
    }
    if (oldVersion <= 57) {
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.LAST_MODIFIED_TIMESTAMP
                + " INTEGER");
        db.execSQL("UPDATE " + DbObject.TABLE + " SET " + DbObject.LAST_MODIFIED_TIMESTAMP + " = "
                + DbObject.TIMESTAMP);
    }
    if (oldVersion <= 58) {
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.GROUP_TYPE + " TEXT DEFAULT 'group'");
        db.execSQL("UPDATE " + Group.TABLE + " SET " + Group.GROUP_TYPE + " = 'group'");
    }
    if (oldVersion <= 59) {
        createIndex(db, "INDEX", "objects_last_modified", DbObject.TABLE, DbObject.LAST_MODIFIED_TIMESTAMP);
    }
    if (oldVersion <= 60) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PUBLIC_KEY_HASH_64
                + " INTEGER DEFAULT 0");
        createIndex(db, "INDEX", "contacts_by_pkp", Contact.TABLE, Contact.PUBLIC_KEY_HASH_64);
        Cursor peeps = db
                .rawQuery("SELECT " + Contact._ID + "," + Contact.PUBLIC_KEY + " FROM " + Contact.TABLE, null);
        peeps.moveToFirst();
        while (!peeps.isAfterLast()) {
            db.execSQL("UPDATE " + Contact.TABLE + " SET " + Contact.PUBLIC_KEY_HASH_64 + " = "
                    + hashPublicKey(peeps.getBlob(1)) + " WHERE " + Contact._ID + " = " + peeps.getLong(0));
            peeps.moveToNext();
        }
        peeps.close();
    }
    db.setVersion(VERSION);
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * update amount of remote file references for article.
 * normally should only be used with {@code null} ("unknown") and {@code 0} (no references)
 *
 * @param id         ID of article, which should be updated
 * @param filesCount new value for remote file references (may be {@code null})
 */// ww  w.ja v  a2  s .  c o  m
public void updateArticleCachedImages(int id, Integer filesCount) {
    if (!isDBAvailable())
        return;

    ContentValues cv = new ContentValues(1);
    if (filesCount == null)
        cv.putNull("cachedImages");
    else
        cv.put("cachedImages", filesCount);

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    try {
        db.update(TABLE_ARTICLES, cv, "_id=?", new String[] { String.valueOf(id) });
    } finally {
        writeLock(false);
    }
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * remove specified mark in the temporary mark table for specified
 * articles and then cleanup this table/*ww  w  .  jav  a2s.c o  m*/
 *
 * @param ids  article IDs, which mark should be reseted
 * @param mark article mark to be reseted
 */
void setMarked(Map<Integer, String> ids, String mark) {
    if (!isDBAvailable())
        return;

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        ContentValues cv = new ContentValues(1);
        for (String idList : StringSupport.convertListToString(ids.keySet(), 1000)) {
            cv.putNull(mark);
            db.update(TABLE_MARK, cv, "id IN(" + idList + ")", null);
            db.delete(TABLE_MARK, "isUnread IS null AND isStarred IS null AND isPublished IS null", null);
        }

        // Insert notes afterwards and only if given note is not null
        cv = new ContentValues(1);
        for (Integer id : ids.keySet()) {
            String note = ids.get(id);
            if (note == null || note.equals(""))
                continue;

            cv.put(MARK_NOTE, note);
            db.update(TABLE_MARK, cv, "id=" + id, null);
        }

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Changes the conflictType for the given row from the specified one to null
 * and set the sync state of this row to the indicated value. In general, you
 * should first update the local conflict record with its new values, then
 * call deleteServerConflictRowWithId(...) and then call this method.
 * //  w ww  . j a va 2s.  c  o m
 * @param db
 * @param tableId
 * @param rowId
 * @param syncState
 * @param conflictType
 */
public void restoreRowFromConflict(SQLiteDatabase db, String tableId, String rowId, SyncState syncState,
        int conflictType) {

    String whereClause = String.format("%s = ? AND %s = ?", DataTableColumns.ID,
            DataTableColumns.CONFLICT_TYPE);
    String[] whereArgs = { rowId, String.valueOf(conflictType) };

    ContentValues cv = new ContentValues();
    cv.putNull(DataTableColumns.CONFLICT_TYPE);
    cv.put(DataTableColumns.SYNC_STATE, syncState.name());
    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        db.update(tableId, cv, whereClause, whereArgs);

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

From source file:org.opendatakit.builder.CsvUtil.java

/**
 * Imports data from a csv file with elementKey headings. This csv file is
 * assumed to be under:/*  w w  w .j a  va2s.c o  m*/
 * <ul>
 * <li>config/assets/csv/tableId.fileQualifier.csv</li>
 * </ul>
 * If the table does not exist, it attempts to create it using the schema and
 * metadata located here:
 * <ul>
 * <li>tables/tableId/definition.csv - data table definition</li>
 * <li>tables/tableId/properties.csv - key-value store</li>
 * </ul>
 *
 * @param importListener     we tell this object our current status every 5 rows, and it updates
 *                           the user's progressdialog
 * @param tableId            the id of the table to import
 * @param fileQualifier      the optional prefix for the filename
 * @param createIfNotPresent whether we should try and create the table
 * @return whether we were successful
 * @throws ServicesAvailabilityException if the database is down
 */
public boolean importSeparable(ImportListener importListener, String tableId, String fileQualifier,
        boolean createIfNotPresent) throws ServicesAvailabilityException {

    DbHandle db = null;
    try {
        db = supervisor.getDatabase().openDatabase(appName);
        if (!supervisor.getDatabase().hasTableId(appName, db, tableId)) {
            if (createIfNotPresent) {
                updateTablePropertiesFromCsv(tableId);
                if (!supervisor.getDatabase().hasTableId(appName, db, tableId)) {
                    return false;
                }
            } else {
                return false;
            }
        }

        OrderedColumns orderedDefns = supervisor.getDatabase().getUserDefinedColumns(appName, db, tableId);

        WebLogger.getLogger(appName).i(TAG, "importSeparable: tableId: " + tableId + " fileQualifier: "
                + (fileQualifier == null ? "<null>" : fileQualifier));

        // reading data
        InputStreamReader input = null;
        try {

            File assetsCsvInstances = new File(ODKFileUtils.getAssetsCsvInstancesFolder(appName, tableId));
            HashSet<File> instancesHavingData = new HashSet<>();
            if (assetsCsvInstances.exists() && assetsCsvInstances.isDirectory()) {
                File[] subDirectories = assetsCsvInstances.listFiles(new FileFilter() {

                    @Override
                    public boolean accept(File pathname) {
                        return pathname.isDirectory() && pathname.list().length != 0;
                    }
                });
                instancesHavingData.addAll(Arrays.asList(subDirectories));
            }

            // both files are read from config/assets/csv directory...
            File assetsCsv = new File(ODKFileUtils.getAssetsCsvFolder(appName));

            // read data table...
            File file = new File(assetsCsv, tableId
                    + (fileQualifier != null && !fileQualifier.isEmpty() ? "." + fileQualifier : "") + ".csv");
            FileInputStream in = new FileInputStream(file);
            input = new InputStreamReader(in, CharEncoding.UTF_8);
            RFC4180CsvReader cr = new RFC4180CsvReader(input);
            // don't have to worry about quotes in elementKeys...
            String[] columnsInFile = cr.readNext();
            int columnsInFileLength = countUpToLastNonNullElement(columnsInFile);

            String v_id;
            String v_form_id;
            String v_locale;
            String v_savepoint_type;
            String v_savepoint_creator;
            String v_savepoint_timestamp;
            String v_row_etag;
            String v_default_access;
            String v_row_owner;
            String v_group_read_only;
            String v_group_modify;
            String v_group_privileged;

            HashMap<String, String> valueMap = new HashMap<>();

            int rowCount = 0;
            String[] row;
            while (true) {
                row = cr.readNext();
                rowCount++;
                if (rowCount % 5 == 0) {
                    importListener.updateProgressDetail(rowCount);
                }
                if (row == null || countUpToLastNonNullElement(row) == 0) {
                    break;
                }
                int rowLength = countUpToLastNonNullElement(row);

                // default values for metadata columns if not provided
                v_id = UUID.randomUUID().toString();
                v_form_id = null;
                v_locale = CursorUtils.DEFAULT_LOCALE;
                v_savepoint_type = SavepointTypeManipulator.complete();
                v_savepoint_creator = CursorUtils.DEFAULT_CREATOR;
                v_savepoint_timestamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
                v_row_etag = null;
                v_default_access = DataTableColumns.DEFAULT_DEFAULT_ACCESS;
                v_row_owner = DataTableColumns.DEFAULT_ROW_OWNER;
                v_group_read_only = DataTableColumns.DEFAULT_GROUP_READ_ONLY;
                v_group_modify = DataTableColumns.DEFAULT_GROUP_MODDIFY;
                v_group_privileged = DataTableColumns.DEFAULT_GROUP_PRIVILEGED;

                // clear value map
                valueMap.clear();

                boolean foundId = false;
                for (int i = 0; i < columnsInFileLength; ++i) {
                    if (i >= rowLength)
                        break;
                    String column = columnsInFile[i];
                    String tmp = row[i];
                    if (DataTableColumns.ID.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            foundId = true;
                            v_id = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.FORM_ID.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_form_id = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.LOCALE.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_locale = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.SAVEPOINT_TYPE.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_savepoint_type = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.SAVEPOINT_CREATOR.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_savepoint_creator = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.SAVEPOINT_TIMESTAMP.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_savepoint_timestamp = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.ROW_ETAG.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_row_etag = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.DEFAULT_ACCESS.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_default_access = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.ROW_OWNER.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_row_owner = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.GROUP_READ_ONLY.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_group_read_only = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.GROUP_MODIFY.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_group_modify = tmp;
                        }
                        continue;
                    }
                    if (DataTableColumns.GROUP_PRIVILEGED.equals(column)) {
                        if (tmp != null && !tmp.isEmpty()) {
                            v_group_privileged = tmp;
                        }
                        continue;
                    }

                    try {
                        orderedDefns.find(column);
                        valueMap.put(column, tmp);
                    } catch (IllegalArgumentException ignored) {
                        // this is OK --
                        // the csv contains an extra column
                    }
                }

                // if there are any conflicts or checkpoints on this row, we do not import
                // this row change. Instead, silently ignore them.
                UserTable table = supervisor.getDatabase().privilegedGetRowsWithId(appName, db, tableId,
                        orderedDefns, v_id);
                if (table.getNumberOfRows() > 1) {
                    WebLogger.getLogger(appName).w(TAG, "importSeparable: tableId: " + tableId + " rowId: "
                            + v_id + " has checkpoints or conflicts -- IGNORED in .csv");
                    continue;
                }

                SyncState syncState = null;
                if (foundId && table.getNumberOfRows() == 1) {
                    String syncStateStr = table.getRowAtIndex(0).getDataByKey(DataTableColumns.SYNC_STATE);
                    if (syncStateStr == null) {
                        throw new IllegalStateException("Unexpected null syncState value");
                    }
                    syncState = SyncState.valueOf(syncStateStr);
                }

                /*
                 * Insertion will set the SYNC_STATE to new_row.
                 *
                 * If the table is sync'd to the server, this will cause one sync
                 * interaction with the server to confirm that the server also has
                 * this record.
                 *
                 * If a record with this same rowId already exists, if it is in an
                 * new_row sync state, we update it here. Otherwise, if there were any
                 * local changes, we leave the row unchanged.
                 */
                if (syncState != null) {

                    ContentValues cv = new ContentValues();
                    for (String column : valueMap.keySet()) {
                        if (column != null) {
                            cv.put(column, valueMap.get(column));
                        }
                    }

                    // The admin columns get added here
                    cv.put(DataTableColumns.FORM_ID, v_form_id);
                    cv.put(DataTableColumns.LOCALE, v_locale);
                    cv.put(DataTableColumns.SAVEPOINT_TYPE, v_savepoint_type);
                    cv.put(DataTableColumns.SAVEPOINT_TIMESTAMP, v_savepoint_timestamp);
                    cv.put(DataTableColumns.SAVEPOINT_CREATOR, v_savepoint_creator);
                    cv.put(DataTableColumns.ROW_ETAG, v_row_etag);
                    cv.put(DataTableColumns.DEFAULT_ACCESS, v_default_access);
                    cv.put(DataTableColumns.ROW_OWNER, v_row_owner);
                    cv.put(DataTableColumns.GROUP_READ_ONLY, v_group_read_only);
                    cv.put(DataTableColumns.GROUP_MODIFY, v_group_modify);
                    cv.put(DataTableColumns.GROUP_PRIVILEGED, v_group_privileged);

                    cv.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
                    cv.putNull(DataTableColumns.CONFLICT_TYPE);

                    if (v_id != null) {
                        cv.put(DataTableColumns.ID, v_id);
                    }

                    if (syncState == SyncState.new_row) {
                        // delete the existing row then insert the new values for it
                        supervisor.getDatabase().privilegedDeleteRowWithId(appName, db, tableId, orderedDefns,
                                v_id);
                        supervisor.getDatabase().privilegedInsertRowWithId(appName, db, tableId, orderedDefns,
                                cv, v_id, true);
                    }
                    // otherwise, do NOT update the row.
                    // i.e., if the row has been sync'd with
                    // the server, then we don't revise it.

                } else {

                    ContentValues cv = new ContentValues();
                    for (String column : valueMap.keySet()) {
                        if (column != null) {
                            cv.put(column, valueMap.get(column));
                        }
                    }

                    // The admin columns get added here
                    cv.put(DataTableColumns.FORM_ID, v_form_id);
                    cv.put(DataTableColumns.LOCALE, v_locale);
                    cv.put(DataTableColumns.SAVEPOINT_TYPE, v_savepoint_type);
                    cv.put(DataTableColumns.SAVEPOINT_TIMESTAMP, v_savepoint_timestamp);
                    cv.put(DataTableColumns.SAVEPOINT_CREATOR, v_savepoint_creator);
                    cv.put(DataTableColumns.ROW_ETAG, v_row_etag);
                    cv.put(DataTableColumns.DEFAULT_ACCESS, v_default_access);
                    cv.put(DataTableColumns.ROW_OWNER, v_row_owner);
                    cv.put(DataTableColumns.GROUP_READ_ONLY, v_group_read_only);
                    cv.put(DataTableColumns.GROUP_MODIFY, v_group_modify);
                    cv.put(DataTableColumns.GROUP_PRIVILEGED, v_group_privileged);

                    cv.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
                    cv.putNull(DataTableColumns.CONFLICT_TYPE);

                    if (v_id == null) {
                        v_id = LocalizationUtils.genUUID();
                    }

                    cv.put(DataTableColumns.ID, v_id);

                    // imports assume super-user level powers. Treat these as if they were
                    // directed by the server during a sync.
                    supervisor.getDatabase().privilegedInsertRowWithId(appName, db, tableId, orderedDefns, cv,
                            v_id, true);
                }

                /*
                 * Copy all attachment files into the destination row.
                 * The attachments are in instance-id-labeled sub-directories.
                 * Anything in the corresponding subdirectory should be
                 * referenced by the valuesMap above. If it isn't, don't worry about
                 * it. This is a simplification.
                 */
                File assetsInstanceFolder = new File(
                        ODKFileUtils.getAssetsCsvInstanceFolder(appName, tableId, v_id));
                if (instancesHavingData.contains(assetsInstanceFolder)) {
                    File tableInstanceFolder = new File(ODKFileUtils.getInstanceFolder(appName, tableId, v_id));
                    tableInstanceFolder.mkdirs();
                    ODKFileUtils.copyDirectory(assetsInstanceFolder, tableInstanceFolder);
                    instancesHavingData.remove(assetsInstanceFolder);
                }

            }
            cr.close();
            return true;
        } catch (IOException ignored) {
            return false;
        } finally {
            try {
                input.close();
            } catch (IOException ignored) {
                // we never even opened the file
            }
        }
    } catch (IOException ignored) {
        return false;
    } finally {
        if (db != null) {
            supervisor.getDatabase().closeDatabase(appName, db);
        }
    }
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void createDBTableMetadata(SQLiteDatabase db, String tableId) {
    if (tableId == null || tableId.length() <= 0) {
        throw new IllegalArgumentException(t + ": application name and table name must be specified");
    }//from   ww  w .jav a 2s  .c o m

    // Add the table id into table definitions
    ContentValues cvTableDef = new ContentValues();
    cvTableDef.put(TableDefinitionsColumns.TABLE_ID, tableId);
    cvTableDef.putNull(TableDefinitionsColumns.SCHEMA_ETAG);
    cvTableDef.putNull(TableDefinitionsColumns.LAST_DATA_ETAG);
    cvTableDef.put(TableDefinitionsColumns.LAST_SYNC_TIME, -1);

    db.replaceOrThrow(DatabaseConstants.TABLE_DEFS_TABLE_NAME, null, cvTableDef);

    // Add the tables values into KVS
    ArrayList<ContentValues> cvTableValKVS = new ArrayList<ContentValues>();

    ContentValues cvTableVal = null;

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_COL_ORDER);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "array");
    cvTableVal.put(KeyValueStoreColumns.VALUE, "[]");
    cvTableValKVS.add(cvTableVal);

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, "defaultViewType");
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "string");
    cvTableVal.put(KeyValueStoreColumns.VALUE, "SPREADSHEET");
    cvTableValKVS.add(cvTableVal);

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_DISPLAY_NAME);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "object");
    cvTableVal.put(KeyValueStoreColumns.VALUE, "\"" + tableId + "\"");
    cvTableValKVS.add(cvTableVal);

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_GROUP_BY_COLS);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "array");
    cvTableVal.put(KeyValueStoreColumns.VALUE, "[]");
    cvTableValKVS.add(cvTableVal);

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_INDEX_COL);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "string");
    cvTableVal.put(KeyValueStoreColumns.VALUE, "");
    cvTableValKVS.add(cvTableVal);

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_SORT_COL);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "string");
    cvTableVal.put(KeyValueStoreColumns.VALUE, "");
    cvTableValKVS.add(cvTableVal);

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_SORT_ORDER);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "string");
    cvTableVal.put(KeyValueStoreColumns.VALUE, "");
    cvTableValKVS.add(cvTableVal);

    cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, "TableColorRuleGroup");
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, "StatusColumn.ruleList");
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "object");
    try {
        List<ColorRule> rules = ColorRuleUtil.getDefaultSyncStateColorRules();
        List<TreeMap<String, Object>> jsonableList = new ArrayList<TreeMap<String, Object>>();
        for (ColorRule rule : rules) {
            jsonableList.add(rule.getJsonRepresentation());
        }
        String value = ODKFileUtils.mapper.writeValueAsString(jsonableList);
        cvTableVal.put(KeyValueStoreColumns.VALUE, value);
        cvTableValKVS.add(cvTableVal);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    // Now add Tables values into KVS
    for (int i = 0; i < cvTableValKVS.size(); i++) {
        db.replaceOrThrow(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, cvTableValKVS.get(i));
    }
}

From source file:com.zns.comicdroid.activity.Edit.java

private void UpdateComics() {
    final ContentValues values = new ContentValues();
    final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this);
    String title = mEtTitle.getText().toString().trim();
    if (title.toLowerCase(Locale.ENGLISH).startsWith("the ")) {
        title = title.substring(4) + ", The";
    }/*from   w  ww  .  ja  v a 2 s.  com*/

    if (mComics != null && mComics.size() > 1) {
        if (!isEmpty(mEtTitle))
            values.put("Title", title);
        if (!isEmpty(mEtSubtitle))
            values.put("SubTitle", mEtSubtitle.getText().toString());
        if (!isEmpty(mEtAuthor))
            values.put("Author", mEtAuthor.getText().toString());
        if (!isEmpty(mEtIllustrator))
            values.put("Illustrator", mEtIllustrator.getText().toString());
        if (!isEmpty(mEtPublisher))
            values.put("Publisher", mEtPublisher.getText().toString());
        if (mSpGroup.getSelectedItemPosition() > 0) {
            Group g = (Group) mSpGroup.getSelectedItem();
            values.put("GroupId", g.getId());
        }
    } else {
        //Strings
        values.put("Title", title);
        values.put("SubTitle", mEtSubtitle.getText().toString());
        values.put("Author", mEtAuthor.getText().toString());
        values.put("Illustrator", mEtIllustrator.getText().toString());
        values.put("Publisher", mEtPublisher.getText().toString());
        values.put("Issues", mEtIssues.getText().toString());
        //Integers
        if (!isEmpty(mEtIssue)) {
            if (isValidInt(mEtIssue.getText().toString())) {
                values.put("Issue", Integer.parseInt(mEtIssue.getText().toString()));
            } else {
                Toast.makeText(this, R.string.edit_issueerror, Toast.LENGTH_LONG).show();
                return;
            }
        } else {
            values.putNull("Issue");
        }
        if (!isEmpty(mEtPageCount)) {
            if (isValidInt(mEtPageCount.getText().toString())) {
                values.put("PageCount", Integer.parseInt(mEtPageCount.getText().toString()));
            } else {
                Toast.makeText(this, R.string.edit_pagecounterror, Toast.LENGTH_LONG).show();
                return;
            }
        } else {
            values.putNull("PageCount");
        }
        //Dates
        try {
            if (!isEmpty(mEtPublished)) {

                values.put("PublishDate",
                        getDBHelper().GetDateStamp(mEtPublished.getText().toString(), dateFormat));
            } else {
                values.putNull("PublishDate");
            }
            if (!isEmpty(mEtAdded)) {
                values.put("AddedDate", getDBHelper().GetDateStamp(mEtAdded.getText().toString(), dateFormat));
            } else {
                values.putNull("AddedDate");
            }
        } catch (ParseException e) {
            Toast.makeText(this, getString(R.string.edit_dateerror) + " " + dateFormat.format(new Date()),
                    Toast.LENGTH_LONG).show();
            return;
        }
        //Image
        if (mNewImage != null) {
            values.put("ImageUrl", "");
            values.put("Image", new File(mNewImage).getName());
        }
        //Group
        if (mSpGroup.getSelectedItemPosition() > 0) {
            Group g = (Group) mSpGroup.getSelectedItem();
            values.put("GroupId", g.getId());
        } else {
            values.putNull("GroupId");
        }
    }

    if (mComics != null) {
        //UPDATE
        StringBuilder sbWhere = new StringBuilder("_id IN (");
        String[] ids = new String[mComics.size()];
        int i = 0;
        for (Comic c : mComics) {
            sbWhere.append("?,");
            ids[i] = Integer.toString(c.getId());
            i++;
        }
        sbWhere.setLength(sbWhere.length() - 1);
        sbWhere.append(")");

        getDBHelper().update("tblBooks", values, sbWhere.toString(), ids);
    } else {
        //INSERT
        if (!values.containsKey("AddedDate") || values.get("AddedDate") == null) {
            values.remove("AddedDate");
            values.put("AddedDate", (int) (System.currentTimeMillis() / 1000L));
        }
        long id = getDBHelper().insert("tblBooks", values);
        Comic comic = getDBHelper().getComic((int) id);
        if (comic != null) {
            mComics = new ArrayList<Comic>();
            mComics.add(comic);
        }
    }

    //Backup
    BackupManager m = new BackupManager(this);
    m.dataChanged();

    setResult(RESULT_OK);

    Toast.makeText(this, getResources().getString(R.string.edit_done), Toast.LENGTH_LONG).show();
}

From source file:reportsas.com.formulapp.Formulario.java

public void insertarEncuentas(EncuestaRespuesta res) {
    try {/*w ww  .  j  a  va2s  .co m*/
        dbAdapter.abrir();
        ContentValues contentValues = new ContentValues();
        contentValues.put("IdUsuario", res.getIdUsuario());
        contentValues.put("IdEncuesta", res.getIdEncuesta());
        contentValues.put("Fecha_Realizacion", res.getFecha());
        contentValues.put("consecutivo", res.getConsecutivo());
        if (dbAdapter.Insertar("Encuesta_Repuesta", contentValues) > 0) {
            for (int i = 0; i < res.getRespuesta().size(); i++) {
                PreguntaRespuesta preguntR = res.getRespuesta().get(i);
                contentValues = new ContentValues();
                contentValues.put("IdUsuario", res.getIdUsuario());
                contentValues.put("IdEncuesta", res.getIdEncuesta());
                contentValues.put("consecutivo", res.getConsecutivo());
                contentValues.put("item", preguntR.getItem());
                contentValues.put("IdPregunta", preguntR.getIdPregunta());
                contentValues.put("repuesta", preguntR.getRespuesta());
                if (preguntR.getOpcion() != null) {

                    contentValues.put("opcion", preguntR.getOpcion());
                } else {
                    contentValues.putNull("opcion");
                }
                if (dbAdapter.Insertar("Pregunta_Respuesta", contentValues) > 0) {

                }
            }

            for (int k = 0; k < res.getParametros().size(); k++) {
                ParametrosRespuesta paramR = res.getParametros().get(k);
                contentValues = new ContentValues();
                contentValues.put("IdUsuario", res.getIdUsuario());
                contentValues.put("IdEncuesta", res.getIdEncuesta());
                contentValues.put("consecutivo", res.getConsecutivo());
                contentValues.put("IdParametro", paramR.getIdParametro());
                contentValues.put("valor", paramR.getValor());
                if (dbAdapter.Insertar("Parametro_Encuesta_Respuesta", contentValues) > 0) {

                }
            }

            Toast toast1 = Toast.makeText(Formulario.this, "Fromulario Enviado", Toast.LENGTH_SHORT);
            toast1.show();
            reiniciarActivity(this, idFormulario);
        }

        dbAdapter.cerrar();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}