Java Code Examples for android.content.ContentValues#clear()

The following examples show how to use android.content.ContentValues#clear() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatabaseHelper.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Restores deleted configuration. Returns the ID of the first one.
 * @return the DI of the restored configuration.
 */
public long restoreDeletedServerConfiguration(final String name) {
	singleArg[0] = name;

	final ContentValues values = this.values;
	values.clear();
	values.put(ConfigurationContract.Configuration.DELETED, 0);
	database.update(Tables.CONFIGURATIONS, values, NAME_SELECTION, singleArg);

	try (Cursor cursor = database.query(Tables.CONFIGURATIONS, ID_PROJECTION, NAME_SELECTION, singleArg,
			null, null, null)) {
		if (cursor.moveToNext())
			return cursor.getLong(0 /* _ID */);
		return -1;
	}
}
 
Example 2
Source File: MainActivity.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
public void insert(View v){
    	//ͨ�������ṩ�ߣ���01��Ŀ��˽�����ݿ��������
    	
    	//��ȡContentResolver
    	ContentResolver cr = getContentResolver();
    	
    	ContentValues values = new ContentValues();
//    	values.put("name", "����");
//    	values.put("money", "13000");
//    	//���insert������ȥ���������ṩ�ߵ�insert����
//    	cr.insert(Uri.parse("content://cn.itcast.person/person"), values);
    	
    	//���values������
    	values.clear();
    	values.put("name", "٩ү");
    	cr.insert(Uri.parse("content://cn.itcast.person/handsome"), values);
    }
 
Example 3
Source File: DbHelper.java    From Beginner-Level-Android-Studio-Apps with GNU General Public License v3.0 6 votes vote down vote up
public void update(String s1,String s2,String s3,String s4,String s5)
{
    db = getWritableDatabase();

    ContentValues value = new ContentValues();

    value.put(column1,s1);
    value.put(column2,s2);
    value.put(column3,s3);
    value.put(column4,s4);
    value.put(column5,s5);

    db.update(table,value,DbHelper.column1+"=?",new String[]{Details.nam});

    value.clear();
    db.close();
}
 
Example 4
Source File: PodDBAdapter.java    From AntennaPodSP with MIT License 6 votes vote down vote up
public void setFeedItemRead(boolean read, long itemId, long mediaId,
                            boolean resetMediaPosition) {
    db.beginTransaction();
    ContentValues values = new ContentValues();

    values.put(KEY_READ, read);
    db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?", new String[]{String.valueOf(itemId)});

    if (resetMediaPosition) {
        values.clear();
        values.put(KEY_POSITION, 0);
        db.update(TABLE_NAME_FEED_MEDIA, values, KEY_ID + "=?", new String[]{String.valueOf(mediaId)});
    }

    db.setTransactionSuccessful();
    db.endTransaction();
}
 
Example 5
Source File: DatabaseHelper.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Marks the configuration with given name as deleted. If may be restored or removed permanently
 * afterwards.
 *
 * @param name the configuration name
 * @return id of the deleted configuration
 */
public long deleteConfiguration(final String name) {
	singleArg[0] = name;

	final ContentValues values = this.values;
	values.clear();
	values.put(ConfigurationContract.Configuration.DELETED, 1);
	database.update(Tables.CONFIGURATIONS, values, NAME_SELECTION, singleArg);

	try (Cursor cursor = database.query(Tables.CONFIGURATIONS, ID_PROJECTION, NAME_SELECTION,
			singleArg, null, null, null)) {
		if (cursor.moveToNext())
			return cursor.getLong(0 /* _ID */);
		return -1;
	}
}
 
Example 6
Source File: DocumentsActivity.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
private void saveStackBlocking() {
    final ContentResolver resolver = getContentResolver();
    final ContentValues values = new ContentValues();

    final byte[] rawStack = DurableUtils.writeToArrayOrNull(mState.stack);
    if (mState.action == ACTION_CREATE || mState.action == ACTION_OPEN_TREE) {
        // Remember stack for last create
        values.clear();
        values.put(RecentColumns.KEY, mState.stack.buildKey());
        values.put(RecentColumns.STACK, rawStack);
        resolver.insert(RecentsProvider.buildRecent(), values);
    }

    // Remember location for next app launch
    final String packageName = getCallingPackageMaybeExtra();
    values.clear();
    values.put(ResumeColumns.STACK, rawStack);
    values.put(ResumeColumns.EXTERNAL, 0);
    resolver.insert(RecentsProvider.buildResume(packageName), values);
}
 
Example 7
Source File: LauncherProvider.java    From LB-Launcher with Apache License 2.0 6 votes vote down vote up
private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
    ArrayList<Long> screenIds = new ArrayList<Long>();
    // TODO: Use multiple loaders with fall-back and transaction.
    int count = loader.loadLayout(db, screenIds);

    // Add the screens specified by the items above
    Collections.sort(screenIds);
    int rank = 0;
    ContentValues values = new ContentValues();
    for (Long id : screenIds) {
        values.clear();
        values.put(LauncherSettings.WorkspaceScreens._ID, id);
        values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
        if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
            throw new RuntimeException("Failed initialize screen table"
                    + "from default layout");
        }
        rank++;
    }

    // Ensure that the max ids are initialized
    mMaxItemId = initializeMaxItemId(db);
    mMaxScreenId = initializeMaxScreenId(db);

    return count;
}
 
Example 8
Source File: SaveHandler.java    From LitePal with Apache License 2.0 5 votes vote down vote up
/**
 * Update the foreign keys in the associated model's table.
 * 
 * @param baseObj
 *            Current model that is persisted.
 */
private void updateAssociatedTableWithFK(LitePalSupport baseObj) {
	Map<String, Set<Long>> associatedModelMap = baseObj.getAssociatedModelsMapWithFK();
	ContentValues values = new ContentValues();
	for (String associatedTableName : associatedModelMap.keySet()) {
		values.clear();
		String fkName = getForeignKeyColumnName(baseObj.getTableName());
		values.put(fkName, baseObj.getBaseObjId());
		Set<Long> ids = associatedModelMap.get(associatedTableName);
		if (ids != null && !ids.isEmpty()) {
			mDatabase.update(associatedTableName, values, getWhereOfIdsWithOr(ids), null);
		}
	}
}
 
Example 9
Source File: NotesDatabase.java    From nextcloud-notes with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Updates a single Note with data from the server, (if it was not modified locally).
 * Thereby, an optimistic concurrency control is realized in order to prevent conflicts arising due to parallel changes from the UI and synchronization.
 * This is used by the synchronization task, hence no Synchronization will be triggered. Use updateNoteAndSync() instead!
 *
 * @param id                        local ID of Note
 * @param remoteNote                Note from the server.
 * @param forceUnchangedDBNoteState is not null, then the local note is updated only if it was not modified meanwhile
 */
void updateNote(LocalAccount localAccount, long id, @NonNull CloudNote remoteNote, @Nullable DBNote forceUnchangedDBNoteState) {
    SQLiteDatabase db = this.getWritableDatabase();

    // First, update the remote ID, since this field cannot be changed in parallel, but have to be updated always.
    ContentValues values = new ContentValues(8);
    values.put(key_remote_id, remoteNote.getRemoteId());
    db.update(table_notes, values, key_id + " = ?", new String[]{String.valueOf(id)});

    // The other columns have to be updated in dependency of forceUnchangedDBNoteState,
    // since the Synchronization-Task must not overwrite locales changes!
    values.clear();
    values.put(key_status, DBStatus.VOID.getTitle());
    values.put(key_title, remoteNote.getTitle());
    values.put(key_modified, remoteNote.getModified().getTimeInMillis() / 1000);
    values.put(key_content, remoteNote.getContent());
    values.put(key_favorite, remoteNote.isFavorite());
    values.put(key_category, getCategoryIdByTitle(localAccount.getId(), remoteNote.getCategory()));
    values.put(key_etag, remoteNote.getEtag());
    values.put(key_excerpt, generateNoteExcerpt(remoteNote.getContent(), remoteNote.getTitle()));
    String whereClause;
    String[] whereArgs;
    if (forceUnchangedDBNoteState != null) {
        // used by: NoteServerSyncHelper.SyncTask.pushLocalChanges()
        // update only, if not modified locally during the synchronization
        // (i.e. all (!) user changeable columns (content, favorite, category) must still have the same value),
        // uses reference value gathered at start of synchronization
        whereClause = key_id + " = ? AND " + key_content + " = ? AND " + key_favorite + " = ? AND " + key_category + " = ?";
        whereArgs = new String[]{String.valueOf(id), forceUnchangedDBNoteState.getContent(), forceUnchangedDBNoteState.isFavorite() ? "1" : "0", String.valueOf(getCategoryIdByTitle(localAccount.getId(), forceUnchangedDBNoteState.getCategory()))};
    } else {
        // used by: NoteServerSyncHelper.SyncTask.pullRemoteChanges()
        // update only, if not modified locally (i.e. STATUS="") and if modified remotely (i.e. any (!) column has changed)
        whereClause = key_id + " = ? AND " + key_status + " = ? AND (" + key_modified + "!=? OR " + key_title + "!=? OR " + key_favorite + "!=? OR " + key_category + "!=? OR " + (remoteNote.getEtag() != null ? key_etag + " IS NULL OR " : "") + key_etag + "!=? OR " + key_content + "!=?)";
        whereArgs = new String[]{String.valueOf(id), DBStatus.VOID.getTitle(), Long.toString(remoteNote.getModified().getTimeInMillis() / 1000), remoteNote.getTitle(), remoteNote.isFavorite() ? "1" : "0", remoteNote.getCategory(), remoteNote.getEtag(), remoteNote.getContent()};
    }
    int i = db.update(table_notes, values, whereClause, whereArgs);
    removeEmptyCategory(id);
    Log.d(TAG, "updateNote: " + remoteNote + " || forceUnchangedDBNoteState: " + forceUnchangedDBNoteState + "  => " + i + " rows updated");
}
 
Example 10
Source File: ContactsHelper.java    From NonViewUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 添加一个联系人数据
 *
 * @return 返回true表示添加成功,false表示失败
 */
public boolean insert(String name, String phoneNumber) {
    //根据号码找数据,如果存在则不添加
    if (getNameByPhoneNumber(phoneNumber) == null) {
        //插入raw_contacts表,并获取_id属性
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = mContext.getContentResolver();
        ContentValues values = new ContentValues();
        long contact_id = ContentUris.parseId(resolver.insert(uri, values));
        //插入data表
        uri = Uri.parse("content://com.android.contacts/data");
        //添加姓名
        values.put("raw_contact_id", contact_id);
        values.put(Data.MIMETYPE, "vnd.android.cursor.item/name");
        values.put("data2", name);
        resolver.insert(uri, values);
        values.clear();
        //添加手机号码
        values.put("raw_contact_id", contact_id);
        values.put(Data.MIMETYPE, "vnd.android.cursor.item/phone_v2");
        values.put("data2", "2");    //2表示手机
        values.put("data1", phoneNumber);
        resolver.insert(uri, values);
        values.clear();
        return true;
    } else {
        return false;
    }
}
 
Example 11
Source File: UpdateUsingUpdateMethodTest.java    From LitePal with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateWithStaticUpdate() {
	ContentValues values = new ContentValues();
	values.put("TEACHERNAME", "Toy");
	int rowsAffected = LitePal.update(Teacher.class, values, teacher.getId());
	assertEquals(1, rowsAffected);
	assertEquals("Toy", getTeacher(teacher.getId()).getTeacherName());
	values.clear();
	values.put("aGe", 15);
	rowsAffected = LitePal.update(Student.class, values, student.getId());
	assertEquals(1, rowsAffected);
	assertEquals(15, getStudent(student.getId()).getAge());
}
 
Example 12
Source File: UpdateHelper.java    From fingen with Apache License 2.0 5 votes vote down vote up
public static void update24(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE ref_Accounts_Sets (_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, FBID TEXT, TS INTEGER, Deleted INTEGER, Dirty INTEGER, LastEdited TEXT, Name TEXT, UNIQUE (Name, Deleted) ON CONFLICT ABORT);");
    db.execSQL("CREATE TABLE log_Accounts_Sets (_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, FBID TEXT, TS INTEGER, Deleted INTEGER, Dirty INTEGER, LastEdited TEXT, SetID INTEGER NOT NULL ON CONFLICT ABORT REFERENCES [ref_Accounts_Sets]([_id]) ON DELETE CASCADE ON UPDATE CASCADE,AccountID INTEGER NOT NULL ON CONFLICT ABORT REFERENCES [ref_Accounts]([_id]) ON DELETE CASCADE ON UPDATE CASCADE,UNIQUE (SetID, AccountID, Deleted) ON CONFLICT ABORT);");

    ContentValues values = new ContentValues();

    values.put("Lat", 0);
    db.update("log_Transactions", values, "Lat IS NULL", null);

    values.clear();
    values.put("Lon", 0);
    db.update("log_Transactions", values, "Lon IS NULL", null);

    values.clear();
    values.put("Accuracy", -1);
    db.update("log_Transactions", values, "Accuracy IS NULL", null);

    values.clear();
    values.put("SimpleDebt", -1);
    db.update("log_Transactions", values, "SimpleDebt IS NULL", null);

    values.clear();
    values.put("ParentID", -1);
    db.update("ref_Categories", values, "ParentID IS NULL", null);

    db.execSQL("CREATE INDEX [idx] ON [log_Transactions] ([Deleted], [DateTime], [SrcAccount], [DestAccount], [Payee], [Category], [Project], [Department], [Location], [SimpleDebt]);");
}
 
Example 13
Source File: PodDBAdapter.java    From AntennaPodSP with MIT License 5 votes vote down vote up
public void setFeedItemRead(boolean read, long... itemIds) {
    db.beginTransaction();
    ContentValues values = new ContentValues();
    for (long id : itemIds) {
        values.clear();
        values.put(KEY_READ, read);
        db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?", new String[]{String.valueOf(id)});
    }
    db.setTransactionSuccessful();
    db.endTransaction();
}
 
Example 14
Source File: DbHelper.java    From GPS2SMS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {

    ContentValues cv = new ContentValues();

    // номер телефона для отправки SMS
    db.execSQL("create table phone (" + "_id integer primary key,"
            + "phone text" + ");");

    // Договорились, что телефон хранится в таблице с _id=1
    cv.put("_id", 1);
    cv.put("phone", ""); // без "+7" !!!
    db.insert("phone", null, cv);

    db.execSQL("create table contact (" + "_id integer primary key,"
            + "contact text" + ");");

    // Договорились, что хранится в таблице с _id=1
    cv.clear();
    cv.put("_id", 1);
    cv.put("contact", "");
    db.insert("contact", null, cv);

    db.execSQL("create table msg (" + "_id integer primary key,"
            + "msg text" + ");");

    // Договорились, что хранится в таблице с _id=1
    cv.clear();
    cv.put("_id", 1);
    cv.put("msg", defSmsMsg);
    db.insert("msg", null, cv);

    Upgrade_1_to_2(db);
    Upgrade_2_to_3(db);
    Upgrade_3_to_4(db);

}
 
Example 15
Source File: DBHelper.java    From fingen with Apache License 2.0 5 votes vote down vote up
public void updateLogProducts(SQLiteDatabase db) throws IOException {
    db.execSQL("DELETE FROM log_Products WHERE TransactionID < 0");

    Cursor cursor = db.rawQuery("SELECT _id, Amount FROM log_Transactions " +
            "WHERE _id not in (SELECT TransactionID FROM log_Products) AND Deleted = 0", null);

    ContentValues cv = new ContentValues();

    if (cursor != null) {
        try {
            if (cursor.moveToFirst()) {
                while (!cursor.isAfterLast()) {
                    cv.clear();
                    cv.put(DBHelper.C_SYNC_FBID, "");
                    cv.put(DBHelper.C_SYNC_TS, -1);
                    cv.put(DBHelper.C_SYNC_DELETED, 0);
                    cv.put(DBHelper.C_SYNC_DIRTY, 0);
                    cv.put(DBHelper.C_SYNC_LASTEDITED, "");
                    cv.put(DBHelper.C_LOG_PRODUCTS_TRANSACTIONID, cursor.getLong(0));
                    cv.put(DBHelper.C_LOG_PRODUCTS_PRODUCTID, 0);
                    cv.put(DBHelper.C_LOG_PRODUCTS_CATEGORY_ID, -1);
                    cv.put(DBHelper.C_LOG_PRODUCTS_PROJECT_ID, -1);
                    cv.put(DBHelper.C_LOG_PRODUCTS_PRICE, cursor.getDouble(1));
                    cv.put(DBHelper.C_LOG_PRODUCTS_QUANTITY, 1);
                    db.insert(DBHelper.T_LOG_PRODUCTS, null, cv);
                    cursor.moveToNext();
                }
            }
        } finally {
            cursor.close();
        }
    }
}
 
Example 16
Source File: Schema.java    From listmyaps with Apache License 2.0 5 votes vote down vote up
private void v1(SQLiteDatabase database) {
	database.execSQL("create table " + TABLE_TEMPLATES + "(" + COLUMN_ID
			+ " integer primary key autoincrement, " + COLUMN_TNAME
			+ " text not null, " + COLUMN_HEADER + " text not null, "
			+ COLUMN_FOOTER + " text not null, " + COLUMN_ITEM
			+ " text not null); ");

	database.execSQL("create table " + TABLE_ANOTATIONS + "(" + COLUMN_PACKID
			+ " text not null, " + COLUMN_COMMENT + " text not null, "
			+ COLUMN_SELECTED + " integer, " + COLUMN_RATING + " integer,"
			+ COLUMN_CATEGORY + " integer);");

	database.execSQL("create table " + TABLE_SELECTION + "(" + COLUMN_PACKID
			+ " text not null, " + COLUMN_SLOTID + " integer, " + COLUMN_SELECTED
			+ " integer);");

	ContentValues values = new ContentValues();
	String[] titles = context.getResources().getStringArray(
			R.array.stdformattitles);
	String[] headers = context.getResources()
			.getStringArray(R.array.stdheaders);
	String[] formats = context.getResources()
			.getStringArray(R.array.stdformats);
	String[] footers = context.getResources()
			.getStringArray(R.array.stdfooters);
	for (int i = 0; i < formats.length; i++) {
		values.put(COLUMN_TNAME, titles[i]);
		values.put(COLUMN_HEADER, headers[i]);
		values.put(COLUMN_ITEM, formats[i]);
		values.put(COLUMN_FOOTER, footers[i]);
		database.insert(Schema.TABLE_TEMPLATES, null, values);
		values.clear();
	}
}
 
Example 17
Source File: DatabaseExampleActivity.java    From coursera-android with MIT License 4 votes vote down vote up
private void insertArtists() {

		ContentValues values = new ContentValues();

		values.put(DatabaseOpenHelper.ARTIST_NAME, "Frank Sinatra");
		mDbHelper.getWritableDatabase().insert(DatabaseOpenHelper.TABLE_NAME, null, values);

		values.clear();

		values.put(DatabaseOpenHelper.ARTIST_NAME, "Lady Gaga");
		mDbHelper.getWritableDatabase().insert(DatabaseOpenHelper.TABLE_NAME, null, values);

		values.clear();

		values.put(DatabaseOpenHelper.ARTIST_NAME, "Jawny Cash");
		mDbHelper.getWritableDatabase().insert(DatabaseOpenHelper.TABLE_NAME, null, values);

		values.clear();

		values.put(DatabaseOpenHelper.ARTIST_NAME, "Ludwig van Beethoven");
		mDbHelper.getWritableDatabase().insert(DatabaseOpenHelper.TABLE_NAME, null, values);
	}
 
Example 18
Source File: SettingsHelper.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the property via a call to the appropriate API, if any, and returns
 * whether or not the setting should be saved to the database as well.
 * @param name the name of the setting
 * @param value the string value of the setting
 * @return whether to continue with writing the value to the database. In
 * some cases the data will be written by the call to the appropriate API,
 * and in some cases the property value needs to be modified before setting.
 */
public void restoreValue(Context context, ContentResolver cr, ContentValues contentValues,
        Uri destination, String name, String value) {
    // Will we need a post-restore broadcast for this element?
    String oldValue = null;
    boolean sendBroadcast = false;
    final SettingsLookup table;

    if (destination.equals(Settings.Secure.CONTENT_URI)) {
        table = sSecureLookup;
    } else if (destination.equals(Settings.System.CONTENT_URI)) {
        table = sSystemLookup;
    } else { /* must be GLOBAL; this was preflighted by the caller */
        table = sGlobalLookup;
    }

    if (sBroadcastOnRestore.contains(name)) {
        // TODO: http://b/22388012
        oldValue = table.lookup(cr, name, UserHandle.USER_SYSTEM);
        sendBroadcast = true;
    }

    try {
        if (Settings.System.SCREEN_BRIGHTNESS.equals(name)) {
            setBrightness(Integer.parseInt(value));
            // fall through to the ordinary write to settings
        } else if (Settings.System.SOUND_EFFECTS_ENABLED.equals(name)) {
            setSoundEffects(Integer.parseInt(value) == 1);
            // fall through to the ordinary write to settings
        } else if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
            setGpsLocation(value);
            return;
        } else if (Settings.Secure.BACKUP_AUTO_RESTORE.equals(name)) {
            setAutoRestore(Integer.parseInt(value) == 1);
        } else if (isAlreadyConfiguredCriticalAccessibilitySetting(name)) {
            return;
        } else if (Settings.System.RINGTONE.equals(name)
                || Settings.System.NOTIFICATION_SOUND.equals(name)) {
            setRingtone(name, value);
            return;
        }

        // Default case: write the restored value to settings
        contentValues.clear();
        contentValues.put(Settings.NameValueTable.NAME, name);
        contentValues.put(Settings.NameValueTable.VALUE, value);
        cr.insert(destination, contentValues);
    } catch (Exception e) {
        // If we fail to apply the setting, by definition nothing happened
        sendBroadcast = false;
    } finally {
        // If this was an element of interest, send the "we just restored it"
        // broadcast with the historical value now that the new value has
        // been committed and observers kicked off.
        if (sendBroadcast) {
            Intent intent = new Intent(Intent.ACTION_SETTING_RESTORED)
                    .setPackage("android").addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY)
                    .putExtra(Intent.EXTRA_SETTING_NAME, name)
                    .putExtra(Intent.EXTRA_SETTING_NEW_VALUE, value)
                    .putExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE, oldValue);
            context.sendBroadcastAsUser(intent, UserHandle.SYSTEM, null);
        }
    }
}
 
Example 19
Source File: LocalyticsProvider.java    From ExtensionsPack with MIT License 4 votes vote down vote up
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion)
{
    /*
     * Delete all sessions in the database, in order to get the data back into a consistent state. This is necessary
     * because an Android bug that caused the database in older versions of the Localytics library to become corrupted.
     */
    if (oldVersion < 3)
    {
        db.delete(UploadBlobEventsDbColumns.TABLE_NAME, null, null);
        db.delete(EventHistoryDbColumns.TABLE_NAME, null, null);
        db.delete(UploadBlobsDbColumns.TABLE_NAME, null, null);
        db.delete(AttributesDbColumns.TABLE_NAME, null, null);
        db.delete(EventsDbColumns.TABLE_NAME, null, null);
        db.delete(SessionsDbColumns.TABLE_NAME, null, null);
    }

    if (oldVersion < 4)
    {
        // if the table is upgraded, it won't have the NOT NULL constraint that is normally present when the table is
        // freshly created
        db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s TEXT;", SessionsDbColumns.TABLE_NAME, SessionsDbColumns.LOCALYTICS_INSTALLATION_ID)); //$NON-NLS-1$
    }

    if (oldVersion < 5)
    {
        db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s TEXT;", SessionsDbColumns.TABLE_NAME, SessionsDbColumns.DEVICE_WIFI_MAC_HASH)); //$NON-NLS-1$
    }

    if (oldVersion < 6)
    {
        Cursor attributesCursor = null;
        try
        {
            attributesCursor = db.query(AttributesDbColumns.TABLE_NAME, new String[]
                {
                    AttributesDbColumns._ID,
                    AttributesDbColumns.ATTRIBUTE_KEY }, null, null, null, null, null);

            final int idColumnIndex = attributesCursor.getColumnIndexOrThrow(AttributesDbColumns._ID);
            final int keyColumnIndex = attributesCursor.getColumnIndexOrThrow(AttributesDbColumns.ATTRIBUTE_KEY);

            final ContentValues tempValues = new ContentValues();
            final String whereClause = String.format("%s = ?", AttributesDbColumns._ID); //$NON-NLS-1$
            final String[] whereArgs = new String[1];

            attributesCursor.moveToPosition(-1);
            while (attributesCursor.moveToNext())
            {
                tempValues.put(AttributesDbColumns.ATTRIBUTE_KEY, String.format(AttributesDbColumns.ATTRIBUTE_FORMAT, mContext.getPackageName(), attributesCursor.getString(keyColumnIndex)));

                whereArgs[0] = Long.toString(attributesCursor.getLong(idColumnIndex));
                db.update(AttributesDbColumns.TABLE_NAME, tempValues, whereClause, whereArgs);

                tempValues.clear();
            }
        }
        finally
        {
            if (null != attributesCursor)
            {
                attributesCursor.close();
                attributesCursor = null;
            }
        }
    }
    
    if (oldVersion < 7)
    {
        // info table
    	db.execSQL(String.format("CREATE TABLE %s (%s TEXT, %s INTEGER);", InfoDbColumns.TABLE_NAME, InfoDbColumns.FB_ATTRIBUTION, InfoDbColumns.FIRST_RUN));
    	final ContentValues values = new ContentValues();
    	values.putNull(InfoDbColumns.FB_ATTRIBUTION);
    	values.put(InfoDbColumns.FIRST_RUN, Boolean.FALSE);
    	db.insertOrThrow(InfoDbColumns.TABLE_NAME, null, values);
    }
    
    if (oldVersion < 8)
    {
        // identifiers table
    	db.execSQL(String.format("CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT UNIQUE NOT NULL, %s TEXT NOT NULL);", IdentifiersDbColumns.TABLE_NAME, IdentifiersDbColumns._ID, IdentifiersDbColumns.KEY, IdentifiersDbColumns.VALUE));	
 
    	// add primary key for information table
    	db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s INTEGER PRIMARY KEY AUTOINCREMENT;", InfoDbColumns.TABLE_NAME, InfoDbColumns._ID)); //$NON-NLS-1$
    }
}
 
Example 20
Source File: MapContentProviderHelper.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    super.onUpgrade(sqLiteDatabase, oldVersion, newVersion);

    Cursor data;
    boolean tableExists = false;

    try {
        data = sqLiteDatabase.query(TrackLayer.TABLE_TRACKS, null, null, null, null, null, null);
        tableExists = true;
        data.close();
    } catch (Exception ignored) { }

    if (oldVersion <= 2 && tableExists) {
        sqLiteDatabase.execSQL("alter table " + TrackLayer.TABLE_TRACKS + " add column " + TrackLayer.FIELD_COLOR + " integer;");

        GeoPoint point = new GeoPoint();
        ContentValues cv = new ContentValues();
        data = sqLiteDatabase.query(TrackLayer.TABLE_TRACKPOINTS,
                new String[]{TrackLayer.FIELD_TIMESTAMP, TrackLayer.FIELD_LON, TrackLayer.FIELD_LAT}, null, null, null, null, null);

        if (data != null) {
            if (data.moveToFirst()) {
                do {
                    point.setCoordinates(data.getDouble(1), data.getDouble(2));
                    point.setCRS(GeoConstants.CRS_WGS84);
                    point.project(GeoConstants.CRS_WEB_MERCATOR);
                    cv.clear();
                    cv.put(TrackLayer.FIELD_LON, point.getX());
                    cv.put(TrackLayer.FIELD_LAT, point.getY());
                    sqLiteDatabase.update(TrackLayer.TABLE_TRACKPOINTS, cv, TrackLayer.FIELD_TIMESTAMP + " = ?", new String[]{data.getLong(0) + ""});
                } while (data.moveToNext());
            }

            data.close();
        }
    }

    if (oldVersion <= 3 && tableExists) {
        sqLiteDatabase.execSQL("alter table " + TrackLayer.TABLE_TRACKPOINTS + " add column " + TrackLayer.FIELD_SENT + " integer not null default 1;");
        sqLiteDatabase.execSQL("alter table " + TrackLayer.TABLE_TRACKPOINTS + " add column " + TrackLayer.FIELD_ACCURACY + " real;");
        sqLiteDatabase.execSQL("alter table " + TrackLayer.TABLE_TRACKPOINTS + " add column " + TrackLayer.FIELD_SPEED + " real;");
    }
}