Search in sources :

Example 16 with DataSupportException

use of org.litepal.exceptions.DataSupportException in project LitePal by LitePalFramework.

the class DataHandler method query.

/**
 * Query the table of the given model, returning a model list over the
 * result set.
 *
 * @param modelClass
 *            The model to compile the query against.
 * @param columns
 *            A list of which columns to return. Passing null will return
 *            all columns, which is discouraged to prevent reading data from
 *            storage that isn't going to be used.
 * @param selection
 *            A filter declaring which rows to return, formatted as an SQL
 *            WHERE clause (excluding the WHERE itself). Passing null will
 *            return all rows for the given table.
 * @param selectionArgs
 *            You may include ?s in selection, which will be replaced by the
 *            values from selectionArgs, in order that they appear in the
 *            selection. The values will be bound as Strings.
 * @param groupBy
 *            A filter declaring how to group rows, formatted as an SQL
 *            GROUP BY clause (excluding the GROUP BY itself). Passing null
 *            will cause the rows to not be grouped.
 * @param having
 *            A filter declare which row groups to include in the cursor, if
 *            row grouping is being used, formatted as an SQL HAVING clause
 *            (excluding the HAVING itself). Passing null will cause all row
 *            groups to be included, and is required when row grouping is
 *            not being used.
 * @param orderBy
 *            How to order the rows, formatted as an SQL ORDER BY clause
 *            (excluding the ORDER BY itself). Passing null will use the
 *            default sort order, which may be unordered.
 * @param limit
 *            Limits the number of rows returned by the query, formatted as
 *            LIMIT clause. Passing null denotes no LIMIT clause.
 * @param foreignKeyAssociations
 *            Associated classes which have foreign keys in the current
 *            model's table.
 * @return A model list. The list may be empty.
 */
@SuppressWarnings("unchecked")
protected <T> List<T> query(Class<T> modelClass, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, List<AssociationsInfo> foreignKeyAssociations) {
    List<T> dataList = new ArrayList<T>();
    Cursor cursor = null;
    try {
        List<Field> supportedFields = getSupportedFields(modelClass.getName());
        List<Field> supportedGenericFields = getSupportedGenericFields(modelClass.getName());
        String[] customizedColumns = DBUtility.convertSelectClauseToValidNames(getCustomizedColumns(columns, supportedGenericFields, foreignKeyAssociations));
        String tableName = getTableName(modelClass);
        cursor = mDatabase.query(tableName, customizedColumns, selection, selectionArgs, groupBy, having, orderBy, limit);
        if (cursor.moveToFirst()) {
            SparseArray<QueryInfoCache> queryInfoCacheSparseArray = new SparseArray<QueryInfoCache>();
            Map<Field, GenericModel> genericModelMap = new HashMap<Field, GenericModel>();
            do {
                T modelInstance = (T) createInstanceFromClass(modelClass);
                giveBaseObjIdValue((DataSupport) modelInstance, cursor.getLong(cursor.getColumnIndexOrThrow("id")));
                setValueToModel(modelInstance, supportedFields, foreignKeyAssociations, cursor, queryInfoCacheSparseArray);
                setGenericValueToModel((DataSupport) modelInstance, supportedGenericFields, genericModelMap);
                if (foreignKeyAssociations != null) {
                    setAssociatedModel((DataSupport) modelInstance);
                }
                dataList.add(modelInstance);
            } while (cursor.moveToNext());
            queryInfoCacheSparseArray.clear();
            genericModelMap.clear();
        }
        return dataList;
    } catch (Exception e) {
        throw new DataSupportException(e.getMessage(), e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) DatabaseGenerateException(org.litepal.exceptions.DatabaseGenerateException) DataSupportException(org.litepal.exceptions.DataSupportException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GenericModel(org.litepal.tablemanager.model.GenericModel) Field(java.lang.reflect.Field) SparseArray(android.util.SparseArray) DataSupportException(org.litepal.exceptions.DataSupportException)

Example 17 with DataSupportException

use of org.litepal.exceptions.DataSupportException in project LitePal by LitePalFramework.

the class DataSupport method saveAll.

/**
 * Saves the collection into database. <br>
 *
 * <pre>
 * DataSupport.saveAll(people);
 * </pre>
 *
 * If the model in collection is a new record gets created in the database,
 * otherwise the existing record gets updated.<br>
 * If saving process failed by any accident, the whole action will be
 * cancelled and your database will be <b>rolled back</b>. <br>
 * This method acts the same result as the below way, but <b>much more
 * efficient</b>.
 *
 * <pre>
 * for (Person person : people) {
 * 	person.save();
 * }
 * </pre>
 *
 * So when your collection holds huge of models,
 * {@link #saveAll(java.util.Collection)} is the better choice.
 *
 * @param collection
 *            Holds all models to save.
 */
public static synchronized <T extends DataSupport> void saveAll(Collection<T> collection) {
    SQLiteDatabase db = Connector.getDatabase();
    db.beginTransaction();
    try {
        SaveHandler saveHandler = new SaveHandler(db);
        saveHandler.onSaveAll(collection);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        throw new DataSupportException(e.getMessage(), e);
    } finally {
        db.endTransaction();
    }
}
Also used : DataSupportException(org.litepal.exceptions.DataSupportException) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) DataSupportException(org.litepal.exceptions.DataSupportException)

Example 18 with DataSupportException

use of org.litepal.exceptions.DataSupportException in project LitePal by LitePalFramework.

the class DataSupport method update.

/**
 * Updates the corresponding record by id. Use setXxx to decide which
 * columns to update.
 *
 * <pre>
 * Person person = new Person();
 * person.setName(&quot;Jim&quot;);
 * person.update(1);
 * </pre>
 *
 * This means that the name of record 1 will be updated into Jim.<br>
 *
 * <b>Note: </b> 1. If you set a default value to a field, the corresponding
 * column won't be updated. Use {@link #setToDefault(String)} to update
 * columns into default value. 2. This method couldn't update foreign key in
 * database. So do not use setXxx to set associations between models.
 *
 * @param id
 *            Which record to update.
 * @return The number of rows affected.
 */
public synchronized int update(long id) {
    try {
        UpdateHandler updateHandler = new UpdateHandler(Connector.getDatabase());
        int rowsAffected = updateHandler.onUpdate(this, id);
        getFieldsToSetToDefault().clear();
        return rowsAffected;
    } catch (Exception e) {
        throw new DataSupportException(e.getMessage(), e);
    }
}
Also used : DataSupportException(org.litepal.exceptions.DataSupportException) DataSupportException(org.litepal.exceptions.DataSupportException)

Example 19 with DataSupportException

use of org.litepal.exceptions.DataSupportException in project LitePal by LitePalFramework.

the class DynamicExecutor method getField.

/**
 * This method use java reflect API to get field value dynamically. Most
 * importantly, it could access fields with private modifier to break
 * encapsulation.
 *
 * @param object
 *            The object to access.
 * @param fieldName
 *            The field name to access.
 * @param objectClass
 *            The class of object.
 * @throws SecurityException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
static Object getField(Object object, String fieldName, Class<?> objectClass) throws IllegalArgumentException, IllegalAccessException {
    if (objectClass == DataSupport.class || objectClass == Object.class) {
        throw new DataSupportException(DataSupportException.noSuchFieldExceptioin(objectClass.getSimpleName(), fieldName));
    }
    try {
        Field objectField = objectClass.getDeclaredField(fieldName);
        objectField.setAccessible(true);
        return objectField.get(object);
    } catch (NoSuchFieldException e) {
        return getField(object, fieldName, objectClass.getSuperclass());
    }
}
Also used : Field(java.lang.reflect.Field) DataSupportException(org.litepal.exceptions.DataSupportException)

Example 20 with DataSupportException

use of org.litepal.exceptions.DataSupportException in project LitePal by LitePalFramework.

the class UpdateHandler method analyzeAssociations.

/**
 * Analyze the associations of baseObj and store the result in it. The
 * associations will be used when deleting referenced data of baseObj.
 * Unused currently.
 *
 * @param baseObj
 *            The record to update.
 */
private void analyzeAssociations(DataSupport baseObj) {
    try {
        Collection<AssociationsInfo> associationInfos = getAssociationInfo(baseObj.getClassName());
        analyzeAssociatedModels(baseObj, associationInfos);
    } catch (Exception e) {
        throw new DataSupportException(e.getMessage(), e);
    }
}
Also used : DataSupportException(org.litepal.exceptions.DataSupportException) AssociationsInfo(org.litepal.crud.model.AssociationsInfo) DataSupportException(org.litepal.exceptions.DataSupportException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

DataSupportException (org.litepal.exceptions.DataSupportException)20 InvocationTargetException (java.lang.reflect.InvocationTargetException)6 Cursor (android.database.Cursor)4 Field (java.lang.reflect.Field)4 DatabaseGenerateException (org.litepal.exceptions.DatabaseGenerateException)4 AssociationsInfo (org.litepal.crud.model.AssociationsInfo)3 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)2 SQLiteException (android.database.sqlite.SQLiteException)2 SparseArray (android.util.SparseArray)2 Teacher (com.litepaltest.model.Teacher)2 Method (java.lang.reflect.Method)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 GenericModel (org.litepal.tablemanager.model.GenericModel)2 ContentValues (android.content.ContentValues)1 Computer (com.litepaltest.model.Computer)1 Student (com.litepaltest.model.Student)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1