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

The following examples show how to use android.database.sqlite.SQLiteDatabase#beginTransactionNonExclusive() . 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: DefaultDownloadIndex.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
private void ensureInitialized() throws DatabaseIOException {
  if (initialized) {
    return;
  }
  try {
    SQLiteDatabase readableDatabase = databaseProvider.getReadableDatabase();
    int version = VersionTable.getVersion(readableDatabase, VersionTable.FEATURE_OFFLINE, name);
    if (version != TABLE_VERSION) {
      SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
      writableDatabase.beginTransactionNonExclusive();
      try {
        VersionTable.setVersion(
            writableDatabase, VersionTable.FEATURE_OFFLINE, name, TABLE_VERSION);
        writableDatabase.execSQL("DROP TABLE IF EXISTS " + tableName);
        writableDatabase.execSQL("CREATE TABLE " + tableName + " " + TABLE_SCHEMA);
        writableDatabase.setTransactionSuccessful();
      } finally {
        writableDatabase.endTransaction();
      }
    }
    initialized = true;
  } catch (SQLException e) {
    throw new DatabaseIOException(e);
  }
}
 
Example 2
Source File: DatabaseHelper.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
public void clearAccess(int uid, boolean keeprules) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            // There is a segmented index on uid
            // There is an index on block
            if (keeprules)
                db.delete("access", "uid = ? AND block < 0", new String[]{Integer.toString(uid)});
            else
                db.delete("access", "uid = ?", new String[]{Integer.toString(uid)});

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

    notifyAccessChanged();
}
 
Example 3
Source File: DatabaseHelper.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
public void setAccess(long id, int block) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            ContentValues cv = new ContentValues();
            cv.put("block", block);
            cv.put("allowed", -1);

            if (db.update("access", cv, "ID = ?", new String[]{Long.toString(id)}) != 1)
                Log.e(TAG, "Set access failed");

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

    notifyAccessChanged();
}
 
Example 4
Source File: DatabaseHelper.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
public void clearAccess() {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            db.delete("access", null, null);

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

    notifyAccessChanged();
}
 
Example 5
Source File: DatabaseHelper.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
public void cleanupLog(long time) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            // There an index on time
            int rows = db.delete("log", "time < ?", new String[]{Long.toString(time)});
            Log.i(TAG, "Cleanup log" +
                    " before=" + SimpleDateFormat.getDateTimeInstance().format(new Date(time)) +
                    " rows=" + rows);

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example 6
Source File: DatabaseHelper.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
public void deleteForward(int protocol, int dport) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            db.delete("forward", "protocol = ? AND dport = ?",
                    new String[]{Integer.toString(protocol), Integer.toString(dport)});

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

    notifyForwardChanged();
}
 
Example 7
Source File: DatabaseHelper.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
public void cleanupLog(long time) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            // There an index on time
            int rows = db.delete("log", "time < ?", new String[]{Long.toString(time)});
            Log.i(TAG, "Cleanup log" +
                    " before=" + SimpleDateFormat.getDateTimeInstance().format(new Date(time)) +
                    " rows=" + rows);

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example 8
Source File: CacheFileMetadataIndex.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes index data for the specified cache.
 *
 * <p>This method may be slow and shouldn't normally be called on the main thread.
 *
 * @param databaseProvider Provides the database in which the index is stored.
 * @param uid The cache UID.
 * @throws DatabaseIOException If an error occurs deleting the index data.
 */
@WorkerThread
public static void delete(DatabaseProvider databaseProvider, long uid)
    throws DatabaseIOException {
  String hexUid = Long.toHexString(uid);
  try {
    String tableName = getTableName(hexUid);
    SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
    writableDatabase.beginTransactionNonExclusive();
    try {
      VersionTable.removeVersion(
          writableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid);
      dropTable(writableDatabase, tableName);
      writableDatabase.setTransactionSuccessful();
    } finally {
      writableDatabase.endTransaction();
    }
  } catch (SQLException e) {
    throw new DatabaseIOException(e);
  }
}
 
Example 9
Source File: CachedContentIndex.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
private static void delete(DatabaseProvider databaseProvider, String hexUid)
    throws DatabaseIOException {
  try {
    String tableName = getTableName(hexUid);
    SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
    writableDatabase.beginTransactionNonExclusive();
    try {
      VersionTable.removeVersion(
          writableDatabase, VersionTable.FEATURE_CACHE_CONTENT_METADATA, hexUid);
      dropTable(writableDatabase, tableName);
      writableDatabase.setTransactionSuccessful();
    } finally {
      writableDatabase.endTransaction();
    }
  } catch (SQLException e) {
    throw new DatabaseIOException(e);
  }
}
 
Example 10
Source File: DatabaseHelper.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
public void deleteForward() {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            db.delete("forward", null, null);

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

    notifyForwardChanged();
}
 
Example 11
Source File: DatabaseHelper.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
public void addForward(int protocol, int dport, String raddr, int rport, int ruid) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            ContentValues cv = new ContentValues();
            cv.put("protocol", protocol);
            cv.put("dport", dport);
            cv.put("raddr", raddr);
            cv.put("rport", rport);
            cv.put("ruid", ruid);

            if (db.insert("forward", null, cv) < 0)
                Log.e(TAG, "Insert forward failed");

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

    notifyForwardChanged();
}
 
Example 12
Source File: CacheFileMetadataIndex.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the index for the given cache UID.
 *
 * <p>This method may be slow and shouldn't normally be called on the main thread.
 *
 * @param uid The cache UID.
 * @throws DatabaseIOException If an error occurs initializing the index.
 */
@WorkerThread
public void initialize(long uid) throws DatabaseIOException {
  try {
    String hexUid = Long.toHexString(uid);
    tableName = getTableName(hexUid);
    SQLiteDatabase readableDatabase = databaseProvider.getReadableDatabase();
    int version =
        VersionTable.getVersion(
            readableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid);
    if (version != TABLE_VERSION) {
      SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
      writableDatabase.beginTransactionNonExclusive();
      try {
        VersionTable.setVersion(
            writableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid, TABLE_VERSION);
        dropTable(writableDatabase, tableName);
        writableDatabase.execSQL("CREATE TABLE " + tableName + " " + TABLE_SCHEMA);
        writableDatabase.setTransactionSuccessful();
      } finally {
        writableDatabase.endTransaction();
      }
    }
  } catch (SQLException e) {
    throw new DatabaseIOException(e);
  }
}
 
Example 13
Source File: CPOrmContentProvider.java    From CPOrm with MIT License 5 votes vote down vote up
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {

    int length = values.length;
    if (length == 0)
        return 0;

    TableDetails tableDetails = uriMatcherHelper.getTableDetails(uri);
    SQLiteDatabase db = database.getWritableDatabase();

    if (debugEnabled) {
        CPOrmLog.d("********* Bulk Insert **********");
        CPOrmLog.d("Uri: " + uri);
    }

    int count = 0;

    try {
        db.beginTransactionNonExclusive();
        String tableName = tableDetails.getTableName();
        for (int i = 0; i < length; i++) {

            db.insertOrThrow(tableName, null, values[i]);
            count++;

            if (count % 100 == 0)
                db.yieldIfContendedSafely();
        }

        db.setTransactionSuccessful();

        notifyChanges(uri.buildUpon().appendQueryParameter(PARAMETER_CHANGE_TYPE, CPOrm.ChangeType.INSERT.toString()).build(), tableDetails);
    } finally {
        db.endTransaction();
    }

    return count;
}
 
Example 14
Source File: DatabaseHelper.java    From NetGuard with GNU General Public License v3.0 5 votes vote down vote up
public void clearApps() {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            db.delete("app", null, null);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example 15
Source File: DbUtils.java    From android-app with GNU General Public License v3.0 5 votes vote down vote up
public static void runInNonExclusiveTx(DaoSession session, Consumer<DaoSession> runnable) {
    SQLiteDatabase db = (SQLiteDatabase) session.getDatabase().getRawDatabase();

    db.beginTransactionNonExclusive();
    try {
        runnable.accept(session);

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 16
Source File: DatabaseHelper.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
public void addApp(String packageName, String label, boolean system, boolean internet, boolean enabled) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            ContentValues cv = new ContentValues();
            cv.put("package", packageName);
            if (label == null)
                cv.putNull("label");
            else
                cv.put("label", label);
            cv.put("system", system ? 1 : 0);
            cv.put("internet", internet ? 1 : 0);
            cv.put("enabled", enabled ? 1 : 0);

            if (db.insert("app", null, cv) < 0)
                Log.e(TAG, "Insert app failed");

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example 17
Source File: DatabaseHelper.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
public void clearApps() {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            db.delete("app", null, null);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example 18
Source File: DbUtils.java    From android-app with GNU General Public License v3.0 5 votes vote down vote up
public static <T> T callInNonExclusiveTx(DaoSession session, Callable<T> callable) {
    SQLiteDatabase db = (SQLiteDatabase) session.getDatabase().getRawDatabase();

    db.beginTransactionNonExclusive();
    try {
        T result = callable.call(session);

        db.setTransactionSuccessful();
        return result;
    } finally {
        db.endTransaction();
    }
}
 
Example 19
Source File: DatabaseHelper.java    From NetGuard with GNU General Public License v3.0 4 votes vote down vote up
public void updateUsage(Usage usage, String dname) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            // There is a segmented index on uid, version, protocol, daddr and dport
            String selection = "uid = ? AND version = ? AND protocol = ? AND daddr = ? AND dport = ?";
            String[] selectionArgs = new String[]{
                    Integer.toString(usage.Uid),
                    Integer.toString(usage.Version),
                    Integer.toString(usage.Protocol),
                    dname == null ? usage.DAddr : dname,
                    Integer.toString(usage.DPort)
            };

            try (Cursor cursor = db.query("access", new String[]{"sent", "received", "connections"}, selection, selectionArgs, null, null, null)) {
                long sent = 0;
                long received = 0;
                int connections = 0;
                int colSent = cursor.getColumnIndex("sent");
                int colReceived = cursor.getColumnIndex("received");
                int colConnections = cursor.getColumnIndex("connections");
                if (cursor.moveToNext()) {
                    sent = cursor.isNull(colSent) ? 0 : cursor.getLong(colSent);
                    received = cursor.isNull(colReceived) ? 0 : cursor.getLong(colReceived);
                    connections = cursor.isNull(colConnections) ? 0 : cursor.getInt(colConnections);
                }

                ContentValues cv = new ContentValues();
                cv.put("sent", sent + usage.Sent);
                cv.put("received", received + usage.Received);
                cv.put("connections", connections + 1);

                int rows = db.update("access", cv, selection, selectionArgs);
                if (rows != 1)
                    Log.e(TAG, "Update usage failed rows=" + rows);
            }

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

    notifyAccessChanged();
}
 
Example 20
Source File: MetadataDbHelper.java    From Android-Keyboard with Apache License 2.0 4 votes vote down vote up
/**
 * Marks a downloading entry as having successfully downloaded and being installed.
 *
 * The metadata database contains information about ongoing processes, typically ongoing
 * downloads. This marks such an entry as having finished and having installed successfully,
 * so it becomes INSTALLED.
 *
 * @param db the metadata database.
 * @param r content values about the entry to mark as processed.
 */
public static void markEntryAsFinishedDownloadingAndInstalled(final SQLiteDatabase db,
        final ContentValues r) {
    switch (r.getAsInteger(TYPE_COLUMN)) {
        case TYPE_BULK:
            DebugLogUtils.l("Ended processing a wordlist");
            // Updating a bulk word list is a three-step operation:
            // - Add the new entry to the table
            // - Remove the old entry from the table
            // - Erase the old file
            // We start by gathering the names of the files we should delete.
            final List<String> filenames = new LinkedList<>();
            final Cursor c = db.query(METADATA_TABLE_NAME,
                    new String[] { LOCAL_FILENAME_COLUMN },
                    LOCALE_COLUMN + " = ? AND " +
                    WORDLISTID_COLUMN + " = ? AND " + STATUS_COLUMN + " = ?",
                    new String[] { r.getAsString(LOCALE_COLUMN),
                            r.getAsString(WORDLISTID_COLUMN),
                            Integer.toString(STATUS_INSTALLED) },
                    null, null, null);
            try {
                if (c.moveToFirst()) {
                    // There should never be more than one file, but if there are, it's a bug
                    // and we should remove them all. I think it might happen if the power of
                    // the phone is suddenly cut during an update.
                    final int filenameIndex = c.getColumnIndex(LOCAL_FILENAME_COLUMN);
                    do {
                        DebugLogUtils.l("Setting for removal", c.getString(filenameIndex));
                        filenames.add(c.getString(filenameIndex));
                    } while (c.moveToNext());
                }
            } finally {
                c.close();
            }
            r.put(STATUS_COLUMN, STATUS_INSTALLED);
            db.beginTransactionNonExclusive();
            // Delete all old entries. There should never be any stalled entries, but if
            // there are, this deletes them.
            db.delete(METADATA_TABLE_NAME,
                    WORDLISTID_COLUMN + " = ?",
                    new String[] { r.getAsString(WORDLISTID_COLUMN) });
            db.insert(METADATA_TABLE_NAME, null, r);
            db.setTransactionSuccessful();
            db.endTransaction();
            for (String filename : filenames) {
                try {
                    final File f = new File(filename);
                    f.delete();
                } catch (SecurityException e) {
                    // No permissions to delete. Um. Can't do anything.
                } // I don't think anything else can be thrown
            }
            break;
        default:
            // Unknown type: do nothing.
            break;
    }
 }