com.raizlabs.android.dbflow.config.FlowManager Java Examples

The following examples show how to use com.raizlabs.android.dbflow.config.FlowManager. 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: FlowQueryList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes all items from the table. Be careful as this will clear data!
 */
@Override
public void clear() {
    Transaction transaction = FlowManager.getDatabaseForTable(internalCursorList.table())
        .beginTransactionAsync(new QueryTransaction.Builder<>(
            SQLite.delete().from(internalCursorList.table())).build())
        .error(internalErrorCallback)
        .success(internalSuccessCallback)
        .build();

    if (transact) {
        transaction.execute();
    } else {
        transaction.executeSync();
    }
}
 
Example #2
Source File: ApplicationController.java    From amiibo with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Fabric.with(this, new Crashlytics(), new Answers());

    _updated = false;
    setInUpdate(false);

    //init the database orm
    FlowManager.init(this);

    //init the AmiiboHelper
    AmiiboHelper.init();

    mApplicationBus = EventBus.builder().build();

    mApplicationBus.register(this);

    AmiitoolFactory.getInstance().init(this);
}
 
Example #3
Source File: DatabaseHelperDelegate.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * If integrity check fails, this method will use the backup db to fix itself. In order to prevent
 * loss of data, please backup often!
 */
public boolean restoreBackUp() {
    boolean success = true;

    File db = FlowManager.getContext().getDatabasePath(TEMP_DB_NAME + getDatabaseDefinition().getDatabaseName());
    File corrupt = FlowManager.getContext().getDatabasePath(getDatabaseDefinition().getDatabaseName());
    if (corrupt.delete()) {
        try {
            writeDB(corrupt, new FileInputStream(db));
        } catch (IOException e) {
            FlowLog.logError(e);
            success = false;
        }
    } else {
        FlowLog.log(FlowLog.Level.E, "Failed to delete DB");
    }
    return success;
}
 
Example #4
Source File: Operator.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
@NonNull
@SuppressWarnings("unchecked")
@Override
public Operator<T> concatenate(@Nullable Object value) {
    operation = new QueryBuilder(Operation.EQUALS).append(columnName()).toString();

    TypeConverter typeConverter = this.typeConverter;
    if (typeConverter == null && value != null) {
        typeConverter = FlowManager.getTypeConverterForClass(value.getClass());
    }
    if (typeConverter != null && convertToDB) {
        value = typeConverter.getDBValue(value);
    }
    if (value instanceof String || value instanceof IOperator
        || value instanceof Character) {
        operation = String.format("%1s %1s ", operation, Operation.CONCATENATE);
    } else if (value instanceof Number) {
        operation = String.format("%1s %1s ", operation, Operation.PLUS);
    } else {
        throw new IllegalArgumentException(
            String.format("Cannot concatenate the %1s", value != null ? value.getClass() : "null"));
    }
    this.value = value;
    isValueSet = true;
    return this;
}
 
Example #5
Source File: DBLocalSearchManager.java    From tysq-android with GNU General Public License v3.0 6 votes vote down vote up
public static void addLocalHistory(String label){
    Log.d("DBLocalSearchManager", "执行到这了");
    ModelAdapter<LocalLabel> manager =
            FlowManager.getModelAdapter(LocalLabel.class);

    LocalLabel oldModel = new Select()
            .from(LocalLabel.class)
            .where(LocalLabel_Table.label.eq(label))
            .querySingle();

    if (oldModel != null){
        manager.delete(oldModel);
    }

    LocalLabel model = new LocalLabel();
    model.setLabel(label);
    manager.insert(model);
    judgeHistoryNum();
}
 
Example #6
Source File: DBLocalDataSourceManager.java    From tysq-android with GNU General Public License v3.0 6 votes vote down vote up
public static void addLocalHistory(String url){
    ModelAdapter<LocalHistoryModel> manager =
            FlowManager.getModelAdapter(LocalHistoryModel.class);

    LocalHistoryModel oldModel = new Select()
            .from(LocalHistoryModel.class)
            .where(LocalHistoryModel_Table.url.eq(url))
            .querySingle();

    if (oldModel != null){
        manager.delete(oldModel);
    }

    LocalHistoryModel model = new LocalHistoryModel();
    model.setUrl(url);
    manager.insert(model);
    judgeHistoryNum();
}
 
Example #7
Source File: MainApplication.java    From AndroidDatabaseLibraryComparison with MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    ActiveAndroid.initialize(new Configuration.Builder(this)
                                     .setDatabaseName("activeandroid")
                                     .setDatabaseVersion(1)
                                     .setModelClasses(SimpleAddressItem.class, AddressItem.class,
                                                      AddressBook.class, Contact.class).create());

    Ollie.with(this)
            .setName("ollie")
            .setVersion(1)
            .setLogLevel(Ollie.LogLevel.FULL)
            .init();

    FlowManager.init(this);

    Sprinkles.init(this, "sprinkles.db", 2);

    RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
    Realm.setDefaultConfiguration(realmConfig);

    mDatabase = getDatabase();
}
 
Example #8
Source File: SqlUtils.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a {@link Uri} from a set of {@link SQLOperator} for specific table.
 *
 * @param modelClass The class of table,
 * @param action     The action to use.
 * @param conditions The set of key-value {@link SQLOperator} to construct into a uri.
 * @return The {@link Uri}.
 */
public static Uri getNotificationUri(@NonNull Class<?> modelClass,
                                     @Nullable Action action,
                                     @Nullable Iterable<SQLOperator> conditions) {
    Uri.Builder uriBuilder = new Uri.Builder().scheme("dbflow")
        .authority(FlowManager.getTableName(modelClass));
    if (action != null) {
        uriBuilder.fragment(action.name());
    }
    if (conditions != null) {
        for (SQLOperator condition : conditions) {
            uriBuilder.appendQueryParameter(Uri.encode(condition.columnName()), Uri.encode(String.valueOf(condition.value())));
        }
    }
    return uriBuilder.build();
}
 
Example #9
Source File: RetrievalAdapter.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
public RetrievalAdapter(@NonNull DatabaseDefinition databaseDefinition) {
    DatabaseConfig databaseConfig = FlowManager.getConfig()
        .getConfigForDatabase(databaseDefinition.getAssociatedDatabaseClassFile());
    if (databaseConfig != null) {
        tableConfig = databaseConfig.getTableConfigForTable(getModelClass());
        if (tableConfig != null) {
            if (tableConfig.singleModelLoader() != null) {
                singleModelLoader = tableConfig.singleModelLoader();
            }

            if (tableConfig.listModelLoader() != null) {
                listModelLoader = tableConfig.listModelLoader();
            }
        }
    }
}
 
Example #10
Source File: FlowCursorList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * @return the full, converted {@link TModel} list from the database on this list. For large
 * data sets that require a large conversion, consider calling this on a BG thread.
 */
@NonNull
public List<TModel> getAll() {
    throwIfCursorClosed();
    warnEmptyCursor();
    if (!cacheModels) {
        return cursor == null ? new ArrayList<TModel>() :
            FlowManager.getModelAdapter(table).getListModelLoader().convertToData(cursor, null);
    } else {
        List<TModel> list = new ArrayList<>();
        for (TModel model : this) {
            list.add(model);
        }
        return list;
    }
}
 
Example #11
Source File: FlowQueryList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Updates a Model {@link Model#update()} . If {@link #transact}
 * is true, this update happens in the BG, otherwise it happens immediately.
 *
 * @param object The object to update
 * @return The updated model.
 */
public TModel set(TModel object) {
    Transaction transaction = FlowManager.getDatabaseForTable(internalCursorList.table())
        .beginTransactionAsync(new ProcessModelTransaction.Builder<>(updateModel)
            .add(object)
            .build())
        .error(internalErrorCallback)
        .success(internalSuccessCallback).build();

    if (transact) {
        transaction.execute();
    } else {
        transaction.executeSync();
    }
    return object;
}
 
Example #12
Source File: FlowQueryList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the full list of {@link TModel} items from the table, removes these from the list, and
 * then deletes the remaining members. This is not that efficient.
 *
 * @param collection The collection if models to keep in the table.
 * @return Always true.
 */
@Override
public boolean retainAll(@NonNull Collection<?> collection) {
    List<TModel> tableList = internalCursorList.getAll();
    tableList.removeAll(collection);
    Transaction transaction = FlowManager.getDatabaseForTable(internalCursorList.table())
        .beginTransactionAsync(new ProcessModelTransaction.Builder<>(tableList, deleteModel)
            .build())
        .error(internalErrorCallback)
        .success(internalSuccessCallback).build();

    if (transact) {
        transaction.execute();
    } else {
        transaction.executeSync();
    }
    return true;
}
 
Example #13
Source File: FlowQueryList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Removes all items from this table in one transaction based on the list passed. This may happen in the background
 * if {@link #transact} is true.
 *
 * @param collection The collection to remove.
 * @return Always true. Will cause a {@link ClassCastException} if the collection is not of type {@link TModel}
 */
@SuppressWarnings("unchecked")
@Override
public boolean removeAll(@NonNull Collection<?> collection) {

    // if its a ModelClass
    Collection<TModel> modelCollection = (Collection<TModel>) collection;
    Transaction transaction = FlowManager.getDatabaseForTable(internalCursorList.table())
        .beginTransactionAsync(new ProcessModelTransaction.Builder<>(deleteModel)
            .addAll(modelCollection).build())
        .error(internalErrorCallback)
        .success(internalSuccessCallback).build();

    if (transact) {
        transaction.execute();
    } else {
        transaction.executeSync();
    }

    return true;
}
 
Example #14
Source File: FlowQueryList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Removes an item from this table on the {@link DefaultTransactionQueue} if
 * {@link #transact} is true.
 *
 * @param object A model class. For interface purposes, this must be an Object.
 * @return true if the item was removed. Always false if the object is not from the same table as this list.
 */
@SuppressWarnings("unchecked")
@Override
public boolean remove(Object object) {
    boolean removed = false;

    // if its a ModelClass
    if (internalCursorList.table().isAssignableFrom(object.getClass())) {
        TModel model = ((TModel) object);
        Transaction transaction = FlowManager.getDatabaseForTable(internalCursorList.table())
            .beginTransactionAsync(new ProcessModelTransaction.Builder<>(deleteModel)
                .add(model).build())
            .error(internalErrorCallback)
            .success(internalSuccessCallback).build();

        if (transact) {
            transaction.execute();
        } else {
            transaction.executeSync();
        }
        removed = true;
    }

    return removed;
}
 
Example #15
Source File: FlowQueryList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Adds an item to this table
 *
 * @param model The model to save
 * @return always true
 */
@Override
public boolean add(@Nullable TModel model) {
    if (model != null) {
        Transaction transaction = FlowManager.getDatabaseForTable(internalCursorList.table())
            .beginTransactionAsync(new ProcessModelTransaction.Builder<>(saveModel)
                .add(model).build())
            .error(internalErrorCallback)
            .success(internalSuccessCallback).build();

        if (transact) {
            transaction.execute();
        } else {
            transaction.executeSync();
        }
        return true;
    } else {
        return false;
    }
}
 
Example #16
Source File: FlowQueryList.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Adds all items to this table.
 *
 * @param collection The list of items to add to the table
 * @return always true
 */
@SuppressWarnings("unchecked")
@Override
public boolean addAll(@NonNull Collection<? extends TModel> collection) {
    // cast to normal collection, we do not want subclasses of this table saved
    final Collection<TModel> tmpCollection = (Collection<TModel>) collection;

    Transaction transaction = FlowManager.getDatabaseForTable(internalCursorList.table())
        .beginTransactionAsync(new ProcessModelTransaction.Builder<>(saveModel)
            .addAll(tmpCollection).build())
        .error(internalErrorCallback)
        .success(internalSuccessCallback).build();

    if (transact) {
        transaction.execute();
    } else {
        transaction.executeSync();
    }
    return true;
}
 
Example #17
Source File: RuuviScannerApplication.java    From com.ruuvi.station with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    me = this;
    Log.d(TAG, "App class onCreate");
    FlowManager.init(getApplicationContext());
    prefs = new Preferences(getApplicationContext());
    ruuviRangeNotifier = new RuuviRangeNotifier(getApplicationContext(), "RuuviScannerApplication");
    Foreground.init(this);
    Foreground.get().addListener(listener);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!foreground) {
                if (prefs.getBackgroundScanMode() == BackgroundScanModes.FOREGROUND) {
                    new ServiceUtils(getApplicationContext()).startForegroundService();
                } else if (prefs.getBackgroundScanMode() == BackgroundScanModes.BACKGROUND) {
                    startBackgroundScanning();
                }
            }
        }
    }, 5000);
    region = new Region("com.ruuvi.station.leRegion", null, null, null);
}
 
Example #18
Source File: TriggerMethod.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
@Override
public String getQuery() {
    QueryBuilder queryBuilder
        = new QueryBuilder(trigger.getQuery())
        .append(methodName);
    if (properties != null && properties.length > 0) {
        queryBuilder.appendSpaceSeparated("OF")
            .appendArray((Object[]) properties);
    }
    queryBuilder.appendSpaceSeparated("ON").append(FlowManager.getTableName(onTable));

    if (forEachRow) {
        queryBuilder.appendSpaceSeparated("FOR EACH ROW");
    }

    if (whenCondition != null) {
        queryBuilder.append(" WHEN ");
        whenCondition.appendConditionToQuery(queryBuilder);
        queryBuilder.appendSpace();
    }

    queryBuilder.appendSpace();

    return queryBuilder.getQuery();
}
 
Example #19
Source File: ModelLoader.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@NonNull
public DatabaseDefinition getDatabaseDefinition() {
    if (databaseDefinition == null) {
        databaseDefinition = FlowManager.getDatabaseForTable(modelClass);
    }
    return databaseDefinition;
}
 
Example #20
Source File: BaseContentProvider.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onCreate() {
    // If this is a module, then we need to initialize the module as part
    // of the creation process. We can assume the framework has been general
    // framework has been initialized.
    if (moduleClass != null) {
        FlowManager.initModule(moduleClass);
    } else if (getContext() != null) {
        FlowManager.init(getContext());
    }

    return true;
}
 
Example #21
Source File: AlterTableMigration.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * @return A List of column definitions that add op to a table in the DB.
 */
public List<String> getColumnDefinitions() {
    String sql = new QueryBuilder(getAlterTableQueryBuilder()).append(FlowManager.getTableName(table)).toString();
    List<String> columnDefinitions = new ArrayList<>();

    if (this.columnDefinitions != null) {
        for (QueryBuilder columnDefinition : this.columnDefinitions) {
            QueryBuilder queryBuilder = new QueryBuilder(sql).appendSpaceSeparated("ADD COLUMN").append(
                columnDefinition.getQuery());
            columnDefinitions.add(queryBuilder.getQuery());
        }
    }

    return columnDefinitions;
}
 
Example #22
Source File: ModelLoader.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@NonNull
public InstanceAdapter<TModel> getInstanceAdapter() {
    if (instanceAdapter == null) {
        instanceAdapter = FlowManager.getInstanceAdapter(modelClass);
    }
    return instanceAdapter;
}
 
Example #23
Source File: App.java    From android-notepad with MIT License 5 votes vote down vote up
@Override
public void onCreate()
{
    super.onCreate();
    CONTEXT = getApplicationContext();
    FlowManager.init(this);
    Stetho.initializeWithDefaults(this);
    configureJobManager();
}
 
Example #24
Source File: Application.java    From MoeGallery with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    sApplication = this;

    sAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
    sAppComponent.inject(this);

    CustomActivityOnCrash.install(this);

    FlowManager.init(this);
}
 
Example #25
Source File: PerfTestDbFlow.java    From android-database-performance with Apache License 2.0 5 votes vote down vote up
private void indexedStringEntityQueriesRun(int count) {
    // create entities
    List<IndexedStringEntity> entities = new ArrayList<>(count);
    String[] fixedRandomStrings = StringGenerator.createFixedRandomStrings(count);
    for (int i = 0; i < count; i++) {
        IndexedStringEntity entity = new IndexedStringEntity();
        entity._id = (long) i;
        entity.indexedString = fixedRandomStrings[i];
        entities.add(entity);
    }
    log("Built entities.");

    // insert entities
    FlowManager.getDatabase(FlowDatabase.class).executeTransaction(insertTransaction(entities, IndexedStringEntity.class));

    log("Inserted entities.");

    // query for entities by indexed string at random
    int[] randomIndices = StringGenerator.getFixedRandomIndices(getQueryCount(), count - 1);

    startClock();
    for (int i = 0; i < getQueryCount(); i++) {
        int nextIndex = randomIndices[i];

        //noinspection unused
        IndexedStringEntity indexedStringEntity = SQLite.select()
                .from(IndexedStringEntity.class)
                .where(IndexedStringEntity_Table.indexedString.eq(
                        fixedRandomStrings[nextIndex]))
                .querySingle();
    }
    stopClock(Benchmark.Type.QUERY_INDEXED);

    // delete all entities
    Delete.table(IndexedStringEntity.class);
    log("Deleted all entities.");
}
 
Example #26
Source File: BaseModelQueriable.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public <QueryClass> QueryClass queryCustomSingle(@NonNull Class<QueryClass> queryModelClass) {
    String query = getQuery();
    FlowLog.log(FlowLog.Level.V, "Executing query: " + query);
    QueryModelAdapter<QueryClass> adapter = FlowManager.getQueryModelAdapter(queryModelClass);
    return cachingEnabled
            ? adapter.getSingleModelLoader().load(query)
            : adapter.getNonCacheableSingleModelLoader().load(query);
}
 
Example #27
Source File: LHApplication.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
@Override
public void onTerminate() {
    super.onTerminate();
    FlowManager.destroy();
    application = null;
    context = null;
}
 
Example #28
Source File: TavernaApplication.java    From incubator-taverna-mobile with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    FlowManager.init(new FlowConfig.Builder(this).build());
    if (BuildConfig.DEBUG) {
        Stetho.initializeWithDefaults(this);
    }

    if (LeakCanary.isInAnalyzerProcess(this)) {
        return;
    }
    LeakCanary.install(this);

}
 
Example #29
Source File: CursorResult.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
CursorResult(Class<TModel> modelClass, @Nullable Cursor cursor) {
    if (cursor != null) {
        this.cursor = FlowCursor.from(cursor);
    }
    retrievalAdapter = FlowManager.getInstanceAdapter(modelClass);
}
 
Example #30
Source File: FlowContentObserver.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the observer for model change events for specific class.
 */
public void registerForContentChanges(@NonNull ContentResolver contentResolver,
                                      @NonNull Class<?> table) {
    contentResolver.registerContentObserver(SqlUtils.getNotificationUri(table, null), true, this);
    REGISTERED_COUNT.incrementAndGet();
    if (!registeredTables.containsValue(table)) {
        registeredTables.put(FlowManager.getTableName(table), table);
    }
}