Java Code Examples for android.database.sqlite.SQLiteDatabase#endTransaction()

The following examples show how to use android.database.sqlite.SQLiteDatabase#endTransaction() . These examples are extracted from open source projects. 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
public int deleteAccount(long id) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {
        String[] sid = new String[]{String.valueOf(id)};
        db.execSQL(UPDATE_ORPHAN_TRANSACTIONS_1, sid);
        db.execSQL(UPDATE_ORPHAN_TRANSACTIONS_2, sid);
        db.delete(TRANSACTION_ATTRIBUTE_TABLE, TransactionAttributeColumns.TRANSACTION_ID
                + " in (SELECT _id from " + TRANSACTION_TABLE + " where " + TransactionColumns.from_account_id + "=?)", sid);
        db.delete(TRANSACTION_TABLE, TransactionColumns.from_account_id + "=?", sid);
        int count = db.delete(ACCOUNT_TABLE, "_id=?", sid);
        db.setTransactionSuccessful();
        return count;
    } finally {
        db.endTransaction();
    }

}
 
Example 2
public List<Integer> GetQid() {
    String coloumns[] = {CORRECTNO};
    SQLiteDatabase db = this.getWritableDatabase();

    db.beginTransaction();
    Cursor cursor = db.query(TABLE_NAME2, coloumns, null, null, null, null, null);
    List<Integer> list = new ArrayList<>();

    while (cursor.moveToNext()) {
        int questionId = cursor.getInt(0);
        list.add(questionId);
    }

    db.setTransactionSuccessful();
    db.endTransaction();
    cursor.close();
    db.close();
    return list;
}
 
Example 3
Source Project: TurboLauncher   File: LauncherProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
    SqlArguments args = new SqlArguments(uri);

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        int numValues = values.length;
        for (int i = 0; i < numValues; i++) {
            addModifiedTime(values[i]);
            if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
                return 0;
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    sendNotify(uri);
    return values.length;
}
 
Example 4
Source Project: android-orm   File: DBProxy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 插入对应实体到数据库
 *
 * @param t
 * @param <T>
 * @return
 */
public final <T extends IDColumn> long insert(T t) {
    if (t == null) {
        throw new NullPointerException("插入对象为NULL");
    }
    ClassInfo<T> classInfo = getClassInfo(t);
    String tableName = classInfo.getTableName();
    ContentValues values = classInfo.getContentValues(t);
    if (values.size() > 0) {
        SQLiteDatabase database = getDatabase();
        database.beginTransaction();
        long id = database.insert(tableName, null, values);
        t.setPrimaryId(id);
        database.setTransactionSuccessful();
        database.endTransaction();
        close(database);
        return id;
    }
    return -1;
}
 
Example 5
Source Project: Liapp   File: DBHelper.java    License: Apache License 2.0 6 votes vote down vote up
public void addScanData(GlucoseData glucosedata) {
    SQLiteDatabase db = getWritableDatabase();


    db.beginTransaction();

    try {
        ContentValues values = new ContentValues();
        values.put(KEY_SCAN_DATE, glucosedata.getDate());
        values.put(KEY_SCAN_GLUCOSELEVEL, glucosedata.getGlucoseLevel());
        values.put(KEY_SCAN_PREDICTION, glucosedata.getPrediction());
        values.put(KEY_SCAN_COMMENT, glucosedata.getComment());

        db.insertOrThrow(TABLE_SCANS, null, values);
        db.setTransactionSuccessful();
    } catch (Exception e) {

    } finally {
        db.endTransaction();
    }
}
 
Example 6
Source Project: tindroid   File: SqlStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean topicDelete(Topic topic) {
    StoredTopic st = (StoredTopic) topic.getLocal();
    boolean success = false;
    if (st != null) {
        SQLiteDatabase db = mDbh.getWritableDatabase();

        try {
            db.beginTransaction();

            MessageDb.deleteAll(db, st.id);
            SubscriberDb.deleteForTopic(db, st.id);
            TopicDb.delete(db, st.id);

            db.setTransactionSuccessful();
            success = true;

            topic.setLocal(null);
        } catch (SQLException ignored) {
        }

        db.endTransaction();
    }

    return success;
}
 
Example 7
Source Project: Capstone-Project   File: PredatorDbHelper.java    License: MIT License 6 votes vote down vote up
public int addCategory(ContentValues contentValues) {
    // Create and/or open the database for writing
    SQLiteDatabase db = getWritableDatabase();

    // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures
    // consistency of the database.
    db.beginTransaction();
    try {
        db.insertOrThrow(PredatorContract.CategoryEntry.TABLE_NAME, null, contentValues);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Logger.e(TAG, "Error while trying to add category to database", e);
    } finally {
        db.endTransaction();
    }
    return contentValues.getAsInteger(PredatorContract.CategoryEntry.COLUMN_CATEGORY_ID);
}
 
Example 8
Source Project: narrate-android   File: PendingSyncCall.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean delete(String name) {
    SQLiteDatabase db = DatabaseHelper.getInstance(GlobalApplication.getAppContext()).getWritableDatabase();
    db.beginTransaction();
    int result = 0;
    try {
        result = db.delete(PENDING_SYNC_CALLS, NAME + "=?", new String[]{name});

        db.setTransactionSuccessful();
    } catch ( Exception e ) {
        e.printStackTrace();
    } finally {
        db.endTransaction();
    }

    return result > 0;
}
 
Example 9
Source Project: tindroid   File: SqlStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean msgDelivered(Topic topic, long messageDbId, Date timestamp, int seq) {
    SQLiteDatabase db = mDbh.getWritableDatabase();
    boolean result = false;
    try {
        db.beginTransaction();

        if (MessageDb.delivered(mDbh.getWritableDatabase(), messageDbId, timestamp, seq) &&
                TopicDb.msgReceived(db, topic, timestamp, seq)) {
            db.setTransactionSuccessful();
            result = true;
        }
    } catch (SQLException ex) {
        Log.w(TAG, "Exception while updating message", ex);
    } finally {
        db.endTransaction();
    }
    return result;
}
 
Example 10
public void cache() {
	SQLiteDatabase db = mHelper.getWritableDatabase();
	db.beginTransaction();
	db.execSQL(Constants.SQL_DROP_TABLE + HomeTimeLineTable.NAME);
	db.execSQL(HomeTimeLineTable.CREATE);
	
	ContentValues values = new ContentValues();
	values.put(HomeTimeLineTable.ID, 1);
	values.put(HomeTimeLineTable.JSON, new Gson().toJson(mMessages));
	
	db.insert(HomeTimeLineTable.NAME, null, values);
	
	db.setTransactionSuccessful();
	db.endTransaction();
}
 
Example 11
/**
 * Handles requests to insert a set of new rows. In Sunshine, we are only going to be
 * inserting multiple rows of data at a time from a weather forecast. There is no use case
 * for inserting a single row of data into our ContentProvider, and so we are only going to
 * implement bulkInsert. In a normal ContentProvider's implementation, you will probably want
 * to provide proper functionality for the insert method as well.
 *
 * @param uri    The content:// URI of the insertion request.
 * @param values An array of sets of column_name/value pairs to add to the database.
 *               This must not be {@code null}.
 *
 * @return The number of values that were inserted.
 */
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    switch (sUriMatcher.match(uri)) {

        case CODE_WEATHER:
            db.beginTransaction();
            int rowsInserted = 0;
            try {
                for (ContentValues value : values) {
                    long weatherDate =
                            value.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
                    if (!SunshineDateUtils.isDateNormalized(weatherDate)) {
                        throw new IllegalArgumentException("Date must be normalized to insert");
                    }

                    long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
                    if (_id != -1) {
                        rowsInserted++;
                    }
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }

            if (rowsInserted > 0) {
                getContext().getContentResolver().notifyChange(uri, null);
            }

            return rowsInserted;

        default:
            return super.bulkInsert(uri, values);
    }
}
 
Example 12
protected <T extends Document<I>, I> void addToDocument(long messageId, String column, List<I> objects, Class<T> clazz) throws IOException {
  SQLiteDatabase database = databaseHelper.getWritableDatabase();
  database.beginTransaction();

  try {
    T document = getDocument(database, messageId, column, clazz);
    document.getList().addAll(objects);
    setDocument(database, messageId, column, document);

    database.setTransactionSuccessful();
  } finally {
    database.endTransaction();
  }
}
 
Example 13
Source Project: NoHttp   File: CookieEntityDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add or update by index(name, domain, path).
 *
 * @param cookie cookie entity.
 */
@Override
public long replace(CookieEntity cookie) {
    SQLiteDatabase database = getWriter();
    database.beginTransaction();

    ContentValues values = new ContentValues();
    values.put(CookieSQLHelper.URI, cookie.getUri());
    values.put(CookieSQLHelper.NAME, cookie.getName());
    values.put(CookieSQLHelper.VALUE, cookie.getValue());
    values.put(CookieSQLHelper.COMMENT, cookie.getComment());
    values.put(CookieSQLHelper.COMMENT_URL, cookie.getCommentURL());
    values.put(CookieSQLHelper.DISCARD, String.valueOf(cookie.isDiscard()));
    values.put(CookieSQLHelper.DOMAIN, cookie.getDomain());
    values.put(CookieSQLHelper.EXPIRY, cookie.getExpiry());
    values.put(CookieSQLHelper.PATH, cookie.getPath());
    values.put(CookieSQLHelper.PORT_LIST, cookie.getPortList());
    values.put(CookieSQLHelper.SECURE, String.valueOf(cookie.isSecure()));
    values.put(CookieSQLHelper.VERSION, cookie.getVersion());
    try {
        long result = database.replace(CookieSQLHelper.TABLE_NAME, null, values);
        database.setTransactionSuccessful();
        return result;
    } catch (Exception e) {
        return -1;
    } finally {
        database.endTransaction();
        closeDateBase(database);
    }
}
 
Example 14
Source Project: android   File: ConcealActivity.java    License: MIT License 5 votes vote down vote up
private void operateDataBase() {
    mBuilder.delete(0, mBuilder.length());

    String content = etOriginalString.getEditableText().toString();
    if (TextUtils.isEmpty(content)) {
        LogUtils.showSnack(etOriginalString, "Content is null!");
        return;
    }

    SQLiteDatabase db = mHelper.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(ConcealDBHelper.NAME, content);
    values.put(ConcealDBHelper.TOKEN, ConcealUtil.encryptString(content));

    printStringEncrypt("Begin transaction");
    try {
        db.beginTransaction();
        db.insert(ConcealDBHelper.TABLE, null, values);
        db.setTransactionSuccessful();

        printStringEncrypt(String.format("Insert: %s", content));

        Cursor cursor = db.query(ConcealDBHelper.TABLE, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(ConcealDBHelper.NAME));
            byte[] encryptToken = cursor.getBlob(cursor.getColumnIndex(ConcealDBHelper.TOKEN));
            String token = ConcealUtil.decryptString(encryptToken);
            printStringEncrypt(String.format("Read: name:%s token:%s", name, token));
        }
        cursor.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.endTransaction();
    }
    printStringEncrypt("End transaction");

    db.close();
}
 
Example 15
private void executeCreate(SQLiteDatabase db) {
	db.beginTransaction();
	try {
		for (TableInfo tableInfo : Cache.getTableInfos()) {
			db.execSQL(SQLiteUtils.createTableDefinition(tableInfo));
		}
		db.setTransactionSuccessful();
	}
	finally {
		db.endTransaction();
	}
}
 
Example 16
@Override
public void deleteSettings(int uid) throws RemoteException {
	try {
		enforcePermission(uid);
		SQLiteDatabase db = getDb();
		if (db == null)
			return;

		mLock.writeLock().lock();
		try {
			db.beginTransaction();
			try {
				db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
				Util.log(null, Log.WARN, "Settings deleted uid=" + uid);

				db.setTransactionSuccessful();
			} finally {
				db.endTransaction();
			}
		} finally {
			mLock.writeLock().unlock();
		}

		// Clear cache
		synchronized (mSettingCache) {
			mSettingCache.clear();
		}
	} catch (Throwable ex) {
		Util.bug(null, ex);
		throw new RemoteException(ex.toString());
	}
}
 
Example 17
public void deleteMessagesInConversation(Conversation conversation) {
    long start = SystemClock.elapsedRealtime();
    final SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    String[] args = {conversation.getUuid()};
    db.delete("messages_index", "uuid in (select uuid from messages where conversationUuid=?)", args);
    int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
    db.setTransactionSuccessful();
    db.endTransaction();
    Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
}
 
Example 18
Source Project: orWall   File: natDBHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion == newVersion){
        return;
    }

    db.beginTransaction();
    try{
        for(int version = oldVersion; version < newVersion; version++){
            switch (version){
                // VERSION 1 -----> 2
                case 1:
                    db.execSQL(String.format("ALTER TABLE %s RENAME TO %s_backup;", NAT_TABLE_NAME, NAT_TABLE_NAME));
                    db.execSQL(NAT_TABLE_CREATE_V2);
                    db.execSQL(String.format(
                            "INSERT INTO %s(%s, %s, %s, %s, %s) SELECT %s, %s, %s, 0, 0 FROM %s_backup;",
                            NAT_TABLE_NAME, COLUMN_APPUID, COLUMN_APPNAME, COLUMN_ONIONTYPE, COLUMN_LOCALHOST, COLUMN_LOCALNETWORK,
                                            COLUMN_APPUID, COLUMN_APPNAME, COLUMN_ONIONTYPE, NAT_TABLE_NAME));
                    db.execSQL(String.format("DROP TABLE %s_backup;", NAT_TABLE_NAME));
            }
        }

        db.setTransactionSuccessful();
    } finally{
        db.endTransaction();
    }
}
 
Example 19
Source Project: android-lite-orm   File: SQLStatement.java    License: Apache License 2.0 4 votes vote down vote up
public int execInsertCollectionWithMapping(SQLiteDatabase db, Collection<?> list, TableManager tableManager) {
    printSQL();
    db.beginTransaction();
    if (OrmLog.isPrint) {
        OrmLog.i(TAG, "----> BeginTransaction[insert col]");
    }
    EntityTable table = null;
    try {
        mStatement = db.compileStatement(sql);
        Iterator<?> it = list.iterator();
        boolean mapTableCheck = true;
        while (it.hasNext()) {
            mStatement.clearBindings();
            Object obj = it.next();

            if (table == null) {
                table = TableManager.getTable(obj);
            }

            int j = 1;
            Object keyObj = null;
            if (table.key != null) {
                keyObj = FieldUtil.getAssignedKeyObject(table.key, obj);
                bind(j++, keyObj);
            }
            if (!Checker.isEmpty(table.pmap)) {
                // 第一个是主键。其他属性从2开始。
                for (Property p : table.pmap.values()) {
                    bind(j++, FieldUtil.get(p.field, obj));
                }
            }
            long rowID = mStatement.executeInsert();
            FieldUtil.setKeyValueIfneed(obj, table.key, keyObj, rowID);
            if (tableManager != null) {
                mapRelationToDb(obj, true, mapTableCheck, db, tableManager);
                mapTableCheck = false;
            }
        }
        if (OrmLog.isPrint) {
            OrmLog.i(TAG, "Exec insert [" + list.size() + "] rows , SQL: " + sql);
        }
        db.setTransactionSuccessful();
        if (OrmLog.isPrint) {
            OrmLog.i(TAG, "----> BeginTransaction[insert col] Successful");
        }
        return list.size();
    } catch (Exception e) {
        if (OrmLog.isPrint) {
            OrmLog.e(TAG, "----> BeginTransaction[insert col] Failling");
        }
        e.printStackTrace();
    } finally {
        realease();
        db.endTransaction();
    }
    return NONE;
}
 
Example 20
/**
     * Handles requests to insert a set of new rows. In Sunshine, we are only going to be
     * inserting multiple rows of data at a time from a weather forecast. There is no use case
     * for inserting a single row of data into our ContentProvider, and so we are only going to
     * implement bulkInsert. In a normal ContentProvider's implementation, you will probably want
     * to provide proper functionality for the insert method as well.
     *
     * @param uri    The content:// URI of the insertion request.
     * @param values An array of sets of column_name/value pairs to add to the database.
     *               This must not be {@code null}.
     *
     * @return The number of values that were inserted.
     */
    @Override
    public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {

        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();

        switch (sUriMatcher.match(uri)) {
//          COMPLETED (2) Only perform our implementation of bulkInsert if the URI matches the CODE_WEATHER code
            case CODE_WEATHER:
                db.beginTransaction();
                int rowsInserted = 0;

                try {
                    for (ContentValues value : values) {
                        long weatherDate = value.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
                        if (!SunshineDateUtils.isDateNormalized(weatherDate)) {
                            throw new IllegalArgumentException("Date must be normalized to insert");
                        }

                        long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
                        if (_id != 0) {
                            rowsInserted++;
                        }
                    }
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }

                if (rowsInserted > 0) {
                    getContext().getContentResolver().notifyChange(uri, null);
                }

//              COMPLETED (3) Return the number of rows inserted from our implementation of bulkInsert
                return rowsInserted;

//          COMPLETED (4) If the URI does match match CODE_WEATHER, return the super implementation of bulkInsert
            default:
                return super.bulkInsert(uri, values);
        }
    }