com.raizlabs.android.dbflow.structure.ModelAdapter Java Examples

The following examples show how to use com.raizlabs.android.dbflow.structure.ModelAdapter. 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: FlowManager.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the table name for the specific model class
 *
 * @param table The class that implements {@link Model}
 * @return The table name, which can be different than the {@link Model} class name
 */
@SuppressWarnings("unchecked")
@NonNull
public static String getTableName(Class<?> table) {
    ModelAdapter modelAdapter = getModelAdapterOrNull(table);
    String tableName = null;
    if (modelAdapter == null) {
        ModelViewAdapter modelViewAdapter = getModelViewAdapterOrNull(table);
        if (modelViewAdapter != null) {
            tableName = modelViewAdapter.getViewName();
        } else {
            throwCannotFindAdapter("ModelAdapter/ModelViewAdapter", table);
        }
    } else {
        tableName = modelAdapter.getTableName();
    }
    return tableName;
}
 
Example #2
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 #3
Source File: CacheableListModelSaver.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void updateAll(@NonNull Collection<TModel> tableCollection,
                                   @NonNull DatabaseWrapper wrapper) {
    // skip if empty.
    if (tableCollection.isEmpty()) {
        return;
    }
    ModelSaver<TModel> modelSaver = getModelSaver();
    ModelAdapter<TModel> modelAdapter = modelSaver.getModelAdapter();
    DatabaseStatement statement = modelAdapter.getUpdateStatement(wrapper);
    try {
        for (TModel model : tableCollection) {
            if (modelSaver.update(model, wrapper, statement)) {
                modelAdapter.storeModelInCache(model);
            }
        }
    } finally {
        statement.close();
    }
}
 
Example #4
Source File: CacheableListModelSaver.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void insertAll(@NonNull Collection<TModel> tableCollection,
                                   @NonNull DatabaseWrapper wrapper) {
    // skip if empty.
    if (tableCollection.isEmpty()) {
        return;
    }

    ModelSaver<TModel> modelSaver = getModelSaver();
    ModelAdapter<TModel> modelAdapter = modelSaver.getModelAdapter();
    DatabaseStatement statement = modelAdapter.getInsertStatement(wrapper);
    try {
        for (TModel model : tableCollection) {
            if (modelSaver.insert(model, statement, wrapper) > 0) {
                modelAdapter.storeModelInCache(model);
            }
        }
    } finally {
        statement.close();
    }
}
 
Example #5
Source File: CacheableListModelSaver.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void saveAll(@NonNull Collection<TModel> tableCollection,
                                 @NonNull DatabaseWrapper wrapper) {
    // skip if empty.
    if (tableCollection.isEmpty()) {
        return;
    }

    ModelSaver<TModel> modelSaver = getModelSaver();
    ModelAdapter<TModel> modelAdapter = modelSaver.getModelAdapter();
    DatabaseStatement statement = modelAdapter.getInsertStatement(wrapper);
    DatabaseStatement updateStatement = modelAdapter.getUpdateStatement(wrapper);
    try {
        for (TModel model : tableCollection) {
            if (modelSaver.save(model, wrapper, statement, updateStatement)) {
                modelAdapter.storeModelInCache(model);
            }
        }
    } finally {
        updateStatement.close();
        statement.close();
    }
}
 
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: DatabaseDefinition.java    From Meteorite with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a full deletion of this database. Reopens the {@link FlowSQLiteOpenHelper} as well.
 *
 * @param context Where the database resides
 */
public void reset(@NonNull Context context) {
    if (!isResetting) {
        isResetting = true;
        getTransactionManager().stopQueue();
        getHelper().closeDB();
        for (ModelAdapter modelAdapter : modelAdapters.values()) {
            modelAdapter.closeInsertStatement();
            modelAdapter.closeCompiledStatement();
        }
        context.deleteDatabase(getDatabaseFileName());

        // recreate queue after interrupting it.
        if (databaseConfig == null || databaseConfig.transactionManagerCreator() == null) {
            transactionManager = new DefaultTransactionManager(this);
        } else {
            transactionManager = databaseConfig.transactionManagerCreator().createManager(this);
        }
        openHelper = null;
        isResetting = false;
        getHelper().getDatabase();
    }
}
 
Example #8
Source File: NotifyDistributor.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@Override
public <TModel> void notifyModelChanged(@NonNull TModel model,
                                        @NonNull ModelAdapter<TModel> adapter,
                                        @NonNull BaseModel.Action action) {
    FlowManager.getModelNotifierForTable(adapter.getModelClass())
        .notifyModelChanged(model, adapter, action);
}
 
Example #9
Source File: FlowManager.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * @param modelClass The class of the table
 * @param <TModel>   The class that implements {@link Model}
 * @return The associated model adapter (DAO) that is generated from a {@link Table} class. Handles
 * interactions with the database. This method is meant for internal usage only.
 * We strongly prefer you use the built-in methods associated with {@link Model} and {@link BaseModel}.
 */
@SuppressWarnings("unchecked")
@NonNull
public static <TModel> ModelAdapter<TModel> getModelAdapter(Class<TModel> modelClass) {
    final ModelAdapter modelAdapter = getModelAdapterOrNull(modelClass);
    if (modelAdapter == null) {
        throwCannotFindAdapter("ModelAdapter", modelClass);
    }
    return modelAdapter;
}
 
Example #10
Source File: SqlUtils.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * Performs necessary logic to notify of {@link Model} changes.
 *
 * @see NotifyDistributor
 */
@SuppressWarnings("unchecked")
@Deprecated
public static <TModel> void notifyModelChanged(@Nullable TModel model,
                                               @NonNull ModelAdapter<TModel> modelAdapter,
                                               @NonNull Action action) {
    NotifyDistributor.get().notifyModelChanged(model, modelAdapter, action);
}
 
Example #11
Source File: CacheableModelLoader.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@NonNull
@SuppressWarnings("unchecked")
public ModelAdapter<TModel> getModelAdapter() {
    if (modelAdapter == null) {
        if (!(getInstanceAdapter() instanceof ModelAdapter)) {
            throw new IllegalArgumentException("A non-Table type was used.");
        }
        modelAdapter = (ModelAdapter<TModel>) getInstanceAdapter();
        if (!modelAdapter.cachingEnabled()) {
            throw new IllegalArgumentException("You cannot call this method for a table that has no caching id. Either" +
                    "use one Primary Key or use the MultiCacheKeyConverter");
        }
    }
    return modelAdapter;
}
 
Example #12
Source File: CacheableListModelLoader.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@NonNull
@SuppressWarnings("unchecked")
public ModelAdapter<TModel> getModelAdapter() {
    if (modelAdapter == null) {
        if (!(getInstanceAdapter() instanceof ModelAdapter)) {
            throw new IllegalArgumentException("A non-Table type was used.");
        }
        modelAdapter = (ModelAdapter<TModel>) getInstanceAdapter();
        if (!modelAdapter.cachingEnabled()) {
            throw new IllegalArgumentException("You cannot call this method for a table that has no caching id. Either" +
                    "use one Primary Key or use the MultiCacheKeyConverter");
        }
    }
    return modelAdapter;
}
 
Example #13
Source File: DatabaseDefinition.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public DatabaseDefinition() {
    databaseConfig = FlowManager.getConfig()
        .databaseConfigMap().get(getAssociatedDatabaseClassFile());


    if (databaseConfig != null) {
        // initialize configuration if exists.
        Collection<TableConfig> tableConfigCollection = databaseConfig.tableConfigMap().values();
        for (TableConfig tableConfig : tableConfigCollection) {
            ModelAdapter modelAdapter = modelAdapters.get(tableConfig.tableClass());
            if (modelAdapter == null) {
                continue;
            }
            if (tableConfig.listModelLoader() != null) {
                modelAdapter.setListModelLoader(tableConfig.listModelLoader());
            }

            if (tableConfig.singleModelLoader() != null) {
                modelAdapter.setSingleModelLoader(tableConfig.singleModelLoader());
            }

            if (tableConfig.modelSaver() != null) {
                modelAdapter.setModelSaver(tableConfig.modelSaver());
            }

        }
        helperListener = databaseConfig.helperListener();
    }
    if (databaseConfig == null || databaseConfig.transactionManagerCreator() == null) {
        transactionManager = new DefaultTransactionManager(this);
    } else {
        transactionManager = databaseConfig.transactionManagerCreator().createManager(this);
    }
}
 
Example #14
Source File: ContentResolverNotifier.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void notifyModelChanged(@NonNull T model, @NonNull ModelAdapter<T> adapter,
                                   @NonNull BaseModel.Action action) {
    if (FlowContentObserver.shouldNotify()) {
        FlowManager.getContext().getContentResolver()
            .notifyChange(SqlUtils.getNotificationUri(adapter.getModelClass(), action,
                adapter.getPrimaryConditionClause(model).getConditions()), null, true);
    }
}
 
Example #15
Source File: DirectModelNotifier.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void notifyModelChanged(@NonNull T model, @NonNull ModelAdapter<T> adapter,
                                   @NonNull BaseModel.Action action) {
    final Set<OnModelStateChangedListener> listeners = modelChangedListenerMap.get(adapter.getModelClass());
    if (listeners != null) {
        for (OnModelStateChangedListener listener : listeners) {
            if (listener != null) {
                listener.onModelChanged(model, action);
            }
        }
    }
}
 
Example #16
Source File: ContentUtils.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the specified model through the {@link android.content.ContentResolver}. Uses the deleteUri
 * to resolve the reference and the model to {@link ModelAdapter#getPrimaryConditionClause(Object)}
 *
 * @param contentResolver The content resolver to use (if different from {@link FlowManager#getContext()})
 * @param deleteUri       A {@link android.net.Uri} from the {@link ContentProvider}
 * @param model           The model to delete
 * @return The number of rows deleted.
 */
@SuppressWarnings("unchecked")
public static <TableClass> int delete(ContentResolver contentResolver, Uri deleteUri, TableClass model) {
    ModelAdapter<TableClass> adapter = (ModelAdapter<TableClass>) FlowManager.getModelAdapter(model.getClass());

    int count = contentResolver.delete(deleteUri, adapter.getPrimaryConditionClause(model).getQuery(), null);

    // reset autoincrement to 0
    if (count > 0) {
        adapter.updateAutoIncrement(model, 0);
    } else {
        FlowLog.log(FlowLog.Level.W, "A delete on " + model.getClass() + " within the ContentResolver appeared to fail.");
    }
    return count;
}
 
Example #17
Source File: ContentUtils.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the model through the {@link android.content.ContentResolver}. Uses the updateUri to
 * resolve the reference and the model to convert its data in {@link android.content.ContentValues}
 *
 * @param contentResolver The content resolver to use (if different from {@link FlowManager#getContext()})
 * @param updateUri       A {@link android.net.Uri} from the {@link ContentProvider}
 * @param model           The model to update
 * @return The number of rows updated.
 */
@SuppressWarnings("unchecked")
public static <TableClass> int update(ContentResolver contentResolver, Uri updateUri, TableClass model) {
    ModelAdapter<TableClass> adapter = (ModelAdapter<TableClass>) FlowManager.getModelAdapter(model.getClass());

    ContentValues contentValues = new ContentValues();
    adapter.bindToContentValues(contentValues, model);
    int count = contentResolver.update(updateUri, contentValues, adapter.getPrimaryConditionClause(model).getQuery(), null);
    if (count == 0) {
        FlowLog.log(FlowLog.Level.W, "Updated failed of: " + model.getClass());
    }
    return count;
}
 
Example #18
Source File: ContentUtils.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts the list of model into the {@link ContentResolver}. Binds all of the models to {@link ContentValues}
 * and runs the {@link ContentResolver#bulkInsert(Uri, ContentValues[])} method. Note: if any of these use
 * autoIncrementing primary keys the ROWID will not be properly updated from this method. If you care
 * use {@link #insert(ContentResolver, Uri, Object)} instead.
 *
 * @param contentResolver The content resolver to use (if different from {@link FlowManager#getContext()})
 * @param bulkInsertUri   The URI to bulk insert with
 * @param table           The table to insert into
 * @param models          The models to insert.
 * @return The count of the rows affected by the insert.
 */
public static <TableClass> int bulkInsert(ContentResolver contentResolver, Uri bulkInsertUri,
                                          Class<TableClass> table, List<TableClass> models) {
    ContentValues[] contentValues = new ContentValues[models == null ? 0 : models.size()];
    ModelAdapter<TableClass> adapter = FlowManager.getModelAdapter(table);

    if (models != null) {
        for (int i = 0; i < contentValues.length; i++) {
            contentValues[i] = new ContentValues();
            adapter.bindToInsertValues(contentValues[i], models.get(i));
        }
    }
    return contentResolver.bulkInsert(bulkInsertUri, contentValues);
}
 
Example #19
Source File: ContentUtils.java    From Meteorite with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts the model into the {@link android.content.ContentResolver}. Uses the insertUri to resolve
 * the reference and the model to convert its data into {@link android.content.ContentValues}
 *
 * @param contentResolver The content resolver to use (if different from {@link FlowManager#getContext()})
 * @param insertUri       A {@link android.net.Uri} from the {@link ContentProvider} class definition.
 * @param model           The model to insert.
 * @return The Uri of the inserted data.
 */
@SuppressWarnings("unchecked")
public static <TableClass> Uri insert(ContentResolver contentResolver, Uri insertUri, TableClass model) {
    ModelAdapter<TableClass> adapter = (ModelAdapter<TableClass>) FlowManager.getModelAdapter(model.getClass());

    ContentValues contentValues = new ContentValues();
    adapter.bindToInsertValues(contentValues, model);
    Uri uri = contentResolver.insert(insertUri, contentValues);
    adapter.updateAutoIncrement(model, Long.valueOf(uri.getPathSegments().get(uri.getPathSegments().size() - 1)));
    return uri;
}
 
Example #20
Source File: DBLocalSearchManager.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
public static void judgeHistoryNum(){
    List<LocalLabel> list = new Select().from(LocalLabel.class).queryList();
    ModelAdapter<LocalLabel> manager = FlowManager.getModelAdapter(LocalLabel.class);
    if (list.size() <= Constant.LOCAL_LABEL_NUM){
        return;
    }

    manager.delete(list.get(0));
}
 
Example #21
Source File: DBLocalDataSourceManager.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
public static void judgeHistoryNum(){
    List<LocalHistoryModel> list = new Select().from(LocalHistoryModel.class).queryList();
    ModelAdapter<LocalHistoryModel> manager = FlowManager.getModelAdapter(LocalHistoryModel.class);
    if (list.size() <= Constant.DATABASE_NUM){
        return;
    }

    manager.delete(list.get(0));
}
 
Example #22
Source File: AppModule.java    From jianshi with Apache License 2.0 5 votes vote down vote up
@Provides
ExclusionStrategy provideExclusionStrategy() {
  return new ExclusionStrategy() {
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
      return false;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
      return clazz.equals(ModelAdapter.class);
    }
  };
}
 
Example #23
Source File: ModelSaver.java    From Meteorite with Apache License 2.0 4 votes vote down vote up
@NonNull
public ModelAdapter<TModel> getModelAdapter() {
    return modelAdapter;
}
 
Example #24
Source File: DatabaseDefinition.java    From Meteorite with Apache License 2.0 4 votes vote down vote up
protected <T> void addModelAdapter(ModelAdapter<T> modelAdapter, DatabaseHolder holder) {
    holder.putDatabaseForTable(modelAdapter.getModelClass(), this);
    modelTableNames.put(modelAdapter.getTableName(), modelAdapter.getModelClass());
    modelAdapters.put(modelAdapter.getModelClass(), modelAdapter);
}
 
Example #25
Source File: PerfTestDbFlow.java    From android-database-performance with Apache License 2.0 4 votes vote down vote up
@NonNull
private <TModel extends Model> ITransaction insertTransaction(Collection entities, Class<TModel> clazz) {
    ModelAdapter<? extends Model> modelAdapter = FlowManager.getModelAdapter(clazz);
    return FastStoreModelTransaction.insertBuilder(modelAdapter).addAll(entities).build();
}
 
Example #26
Source File: PerfTestDbFlow.java    From android-database-performance with Apache License 2.0 4 votes vote down vote up
@NonNull
private <TModel extends Model> ITransaction updateTransaction(Collection entities, Class<TModel> clazz) {
    ModelAdapter<? extends Model> modelAdapter = FlowManager.getModelAdapter(clazz);
    return FastStoreModelTransaction.updateBuilder(modelAdapter).addAll(entities).build();
}
 
Example #27
Source File: FlowManager.java    From Meteorite with Apache License 2.0 4 votes vote down vote up
@Nullable
private static <T> ModelAdapter<T> getModelAdapterOrNull(Class<T> modelClass) {
    return FlowManager.getDatabaseForTable(modelClass).getModelAdapterForTable(modelClass);
}
 
Example #28
Source File: ModelSaver.java    From Meteorite with Apache License 2.0 4 votes vote down vote up
public void setModelAdapter(@NonNull ModelAdapter<TModel> modelAdapter) {
    this.modelAdapter = modelAdapter;
}
 
Example #29
Source File: ModelNotifier.java    From Meteorite with Apache License 2.0 4 votes vote down vote up
<T> void notifyModelChanged(@NonNull T model, @NonNull ModelAdapter<T> adapter,
@NonNull BaseModel.Action action);
 
Example #30
Source File: FlowCursorList.java    From Meteorite with Apache License 2.0 4 votes vote down vote up
@NonNull
ModelAdapter<TModel> getModelAdapter() {
    return (ModelAdapter<TModel>) instanceAdapter;
}