GithubHelp home page GithubHelp logo

j256 / ormlite-android Goto Github PK

View Code? Open in Web Editor NEW
1.6K 1.6K 368.0 593 KB

ORMLite Android functionality used in conjunction with ormlite-core

Home Page: http://ormlite.com/

License: ISC License

Java 100.00%
android java orm

ormlite-android's People

Contributors

dant3 avatar emmby avatar j256 avatar ncrouther avatar sanderderks avatar vladad avatar wonshaw avatar yanchenko avatar yuriy-blinov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ormlite-android's Issues

timestamp type can not be assigned

java.sql.SQLException: Could not assign object 'Thu Aug 07 11:09:25 EDT 2014' to field FieldType:name=created_time,class=Homework

I got this warming when I query "Homeworks"

and I define my created_time as

public class Homework {
    @DatabaseField(generatedId = true)
    private Integer id;
    @DatabaseField
    private String URI;
    @DatabaseField
    private Integer assignment_id;
    @DatabaseField(dataType = DataType.TIME_STAMP, format = "yyyy-MM-dd HH:mm:ss")
    private Timestamp created_time;
    @DatabaseField
    private String title;
}

I searched for stackoverflow and tried some solutions but did work it out.

OrmLite Loaders and database connection loss at configuration changes

Hi,

I'm facing a database connection issue after configuration changes.
I'm using a single activity which extends OrmLiteBaseActivity. I also use an OrmLiteQueryForAllLoader in this activity to load my persisted objects.
At configuration changes, the activity is destroyed, so the database helper close the database connection since nobody use it anymore. Then the activity is recreated, leading to a new database connection.
The problem is that OrmLiteQueryForAllLoader (which is kept alive even at configuration changes) retains a Dao object with the first created dabase connection. After a configuration change, this connection is closed and this leads to a IllegalStateException since the retained Dao tries to use a closed connection.

We need a way to keep the connection opened even when all activities are destroyed, maybe by retaining it in the loaders ?

Does ORMLite support alter table?

Does Ormlite support alter table? I had some field to add to the table when the database onUpgrade, but I don't want to drop the table, and want to retain the data. How do I do it?

Annotation Processing not working in Android 2.3

I´m not familiar with your code and I don´t have enough knowledge to find out exactly it´s not working, but here is the case:

I tested the master branch on Android 4.4 an worked like a charm, but when testing using Android 2.3, I got a lot of errors in the annotated fields I debug the code in both devices (2.3 and 4.4) and notice that the difference was in the lookupClassesmethod in DatabaseTableConfigUtil, for some reason in Android 4.4 Class.forName("org.apache.harmony.lang.annotation.AnnotationFactory"); throws an exception and the method returns null.

I guess using apache AnnotationFactory it´s an attempt to optimize the annotations processing, but for some reason when this method is used in Android 2.3 (probably in others version as well) something goes wrong and the annotation process does not work, simple removing lookupClassesmethod was enough to fix the issue.

By annotation not working I mean get random errors like:
"Field x has maxForeignAutoRefreshLevel set 2 but foreignAutoRefresh is false" in a primitive field annotated only with @DatabaseField

database is locked: retrycount exceeded

HI, In my project the following exception has been encountered, I have multi-thread, and different process to access the db. And I'm sure that I only have one helper.

E/SqliteCursor.cpp( 8057): Bailing on database busy retry

E/SQLiteQuery( 8057): exception: database is locked: retrycount exceeded; query: SELECT * FROM t_wkItem

W/System.err( 8057): java.sql.SQLException: Problems executing Android query: SELECT * FROM t_wkItem

W/System.err( 8057): at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)

W/System.err( 8057): at com.j256.ormlite.android.AndroidCompiledStatement.getCursor(AndroidCompiledStatement.java:166)

W/System.err( 8057): at com.j256.ormlite.android.AndroidCompiledStatement.runQuery(AndroidCompiledStatement.java:57)

W/System.err( 8057): at com.j256.ormlite.stmt.SelectIterator.(SelectIterator.java:55)

W/System.err( 8057): at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java:232)

W/System.err( 8057): at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:181)

W/System.err( 8057): at com.j256.ormlite.dao.BaseDaoImpl.query(BaseDaoImpl.java:263)

W/System.err( 8057): at com.j256.ormlite.stmt.QueryBuilder.query(QueryBuilder.java:319)

W/System.err( 8057): at com.j256.ormlite.stmt.Where.query(Where.java:485)

W/System.err( 8057): at com.tocel.patrol.app.SubmitOffLinePatrolResultService.submitItemResult(SubmitOffLinePatrolResultService.java:297)

W/System.err( 8057): at com.tocel.patrol.app.SubmitOffLinePatrolResultService.access$1(SubmitOffLinePatrolResultService.java:275)

W/System.err( 8057): at com.tocel.patrol.app.SubmitOffLinePatrolResultService$1.run(SubmitOffLinePatrolResultService.java:144)

W/System.err( 8057): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)

W/System.err( 8057): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

W/System.err( 8057): at java.util.concurrent.FutureTask.run(FutureTask.java:137)

W/System.err( 8057): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)

W/System.err( 8057): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)

W/System.err( 8057): at java.lang.Thread.run(Thread.java:856)

W/System.err( 8057): Caused by: android.database.sqlite.SQLiteDatabaseLockedException: database is locked: retrycount exceeded

W/System.err( 8057): at android.database.sqlite.SQLiteQuery.nativeFillWindow(Native Method)

W/System.err( 8057): at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:86)

W/System.err( 8057): at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:164)

W/System.err( 8057): at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:156)

W/System.err( 8057): at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:161)

W/System.err( 8057): at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:201)

W/System.err( 8057): at com.j256.ormlite.android.AndroidCompiledStatement.getCursor(AndroidCompiledStatement.java:163)

W/System.err( 8057): ... 16 more

Error when run android application

Hi! I receive sometime some error when run application.

java.lang.NullPointerException
at com.j256.ormlite.field.FieldType.resultToJava(FieldType.java:819)
at com.j256.ormlite.stmt.mapped.BaseMappedQuery.mapRow(BaseMappedQuery.java:60)
at com.j256.ormlite.android.AndroidDatabaseConnection.queryForOne(AndroidDatabaseConnection.java:196)
at com.j256.ormlite.stmt.mapped.MappedQueryForId.execute(MappedQueryForId.java:38)
at com.j256.ormlite.field.FieldType.assignField(FieldType.java:558)
at com.j256.ormlite.stmt.mapped.BaseMappedQuery.mapRow(BaseMappedQuery.java:71)
at com.j256.ormlite.stmt.SelectIterator.getCurrent(SelectIterator.java:270)
at com.j256.ormlite.stmt.SelectIterator.nextThrow(SelectIterator.java:161)
at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:202)
at com.j256.ormlite.stmt.StatementExecutor.queryForAll(StatementExecutor.java:118)
at com.j256.ormlite.dao.BaseDaoImpl.queryForAll(BaseDaoImpl.java:241)
at com.****.core.database.dao.ShoppingCartDAO.getAll(ShoppingCartDAO.java:199)

I write logic like this guide::
http://habrahabr.ru/post/143431/

The application may be doing too much work on its main thread

Hi Grey! I received exception when update database!!
Here is log:
{code}
00:21 I/Choreographer: Skipped 752 frames! The application may be doing too much work on its main thread.
00:21 I/dalvikvm-heap: Grow heap (frag case) to 12.850MB for 1718978-byte allocation
00:21 I/dalvikvm-heap: Grow heap (frag case) to 16.058MB for 3409936-byte allocation
00:21 I/TableUtils: creating table 'credit_card'
00:23 I/Choreographer: Skipped 92 frames! The application may be doing too much work on its main thread.
00:23 I/dalvikvm-heap: Grow heap (frag case) to 17.823MB for 1718976-byte allocation
00:24 I/TableUtils: executed create table statement changed 0 rows: CREATE TABLE IF NOT EXISTS credit_card (credit_card_ccv VARCHAR , credit_card_address_1 VARCHAR , credit_card_address_2 VARCHAR , credit_card_address_city VARCHAR , credit_card_address_country VARCHAR , credit_card_address_first_name VARCHAR , credit_card_address_id VARCHAR , credit_card_address_last_name VARCHAR , credit_card_address_phone VARCHAR , credit_card_address_state VARCHAR , credit_card_address_zip_code VARCHAR , credit_card_expiration_month VARCHAR , credit_card_expiration_year VARCHAR , credit_card_full_number VARCHAR , credit_card_id VARCHAR , credit_card_last_digit VARCHAR , credit_card_type VARCHAR , credit_card_type_id VARCHAR , credit_card_address_uri VARCHAR , credit_card_name VARCHAR , credit_card_first_name VARCHAR , credit_card_user_id VARCHAR , credit_card_last_name VARCHAR , credit_card_is_saved SMALLINT , credit_card_is_save_required SMALLINT , id INTEGER PRIMARY KEY AUTOINCREMENT )
00:30 I/Choreographer: Skipped 41 frames! The application may be doing too much work on its main thread.
00:32 I/TableUtils: creating table 'deal'
{code}

And stack:
{code}
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.j256.ormlite.db.BaseDatabaseType.appendColumnArg(BaseDatabaseType.java:64)
at com.j256.ormlite.table.TableUtils.addCreateTableStatements(TableUtils.java:334)
at com.j256.ormlite.table.TableUtils.doCreateTable(TableUtils.java:439)
at com.j256.ormlite.table.TableUtils.createTable(TableUtils.java:220)
at com.j256.ormlite.table.TableUtils.createTableIfNotExists(TableUtils.java:61)
at com.ls.dailysteals.core.database.DB.onCreate(DB.java:81)
at com.ls.dailysteals.core.database.DB.onUpgrade(DB.java:138)
at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.onUpgrade(OrmLiteSqliteOpenHelper.java:240)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.j256.ormlite.android.AndroidConnectionSource.getReadWriteConnection(AndroidConnectionSource.java:66)
at com.j256.ormlite.dao.BaseDaoImpl.callBatchTasks(BaseDaoImpl.java:626)
at com.ls._.ui.fragment.IceMonkeyFragment$3.doInBackground(IceMonkeyFragment.java:175)
at com.ls.
_.ui.fragment.IceMonkeyFragment$3.doInBackground(IceMonkeyFragment.java:170)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 3 more
{code}

{code}
@OverRide
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {

    // drop all tables when database version latest 4 because database structure cardinal changes.
    if (oldVer < DATABASE_VERSION) {
        List<String> tables = new ArrayList<String>();
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            String tableName = cursor.getString(1);
            if (!tableName.equals("android_metadata") && !tableName.equals("sqlite_sequence"))
                tables.add(tableName);
            cursor.moveToNext();
        }
        cursor.close();

        for (String tableName : tables) {
            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + tableName);
        }
    }

    onCreate(sqLiteDatabase, connectionSource);
}

{code}

column not found in micromax

I am getting the following exception only on Micromax A350.
Exception: java.lang.IllegalArgumentException: Unknown column name 'xyzcolumn' in table abctable
I am using progaurd and i have added the progaurd rules for ormlite, but still problem persists.
This is happening when I generated apk from linux machine.

DatabaseTableConfig for foreign collection

Hi,
I want to create DatabaseTableConfigs for two classes, with a one-to-many relationship:

Take this as example:

class A {
   String uuid;
   Collection<B> bs;
}

class B {
   String uuid;
   A a;
}

I get No fields have a DatabaseField annotation in class B with my current setup and I can not find any help regarding this problem.

I have something like this as my current config:

....
TableUtils.createTable(connectionSource, getATableConfig());
TableUtils.createTable(connectionSource, getBTableConfig());

....

DatabaseTableConfig<A> getATableConfig() {
    List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>();

    DatabaseFieldConfig fieldUuid = new DatabaseFieldConfig("uuid");
    fieldUuid.setCanBeNull(false);
    fieldUuid.setId(true);
    fieldConfigs.add(fieldUuid);

   DatabaseFieldConfig fieldBs = new DatabaseFieldConfig("bs");
   fieldBs.setCanBeNull(true);
   fieldBs.setForeignCollection(true);
   fieldBs.setForeignCollectionEager(true);
   fieldBs.setForeignCollectionForeignFieldName("a");
   fieldConfigs.add(fieldBs);

   return new DatabaseTableConfig<>(A.class, fieldConfigs);
}

DatabaseTableConfig<B> getBTableConfig() {
    List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>();

    DatabaseFieldConfig fieldUuid = new DatabaseFieldConfig("uuid");
    fieldUuid.setCanBeNull(false);
    fieldUuid.setId(true);
    fieldConfigs.add(fieldUuid);

    DatabaseFieldConfig fieldA = new DatabaseFieldConfig("a");
    fieldA.setCanBeNull(true);
    fieldA.setForeign(true);
    fieldA.setForeignAutoRefresh(true);
    fieldA.setForeignTableConfig(getATableConfig());
    fieldConfigs.add(fieldA);

    return new DatabaseTableConfig<>(B.class, fieldConfigs);
}

Android Gingerbread INSTALL_FAILED_DEXOPT

We are developing an application, and when we use this library we get INSTALL_FAILED_DEXOPT. This behavior is happening only on Gingerbread. In logcat we get this erorr:
LinearAlloc exceeded capacity (5242880), last=4108
After we've done some research on this mater we found that has something to do with how complex the application is using abstractizations (abstract classes and interfaces).
https://code.google.com/p/android/issues/detail?id=22586

NullPointerException on queryBuilder

In Google Analytics I have the following records:

...
    2.  NullPointerException (@PlayList:getDatabaseAlbum:386) {Thread-108}
    3.  NullPointerException (@PlayList:getDatabaseAlbum:386) {Thread-11086}    
    4.  NullPointerException (@PlayList:getDatabaseAlbum:386) {Thread-11189}    
    5.  NullPointerException (@PlayList:getDatabaseAlbum:386) {Thread-1125} 
    6.  NullPointerException (@PlayList:getDatabaseAlbum:386) {Thread-1194} 
    7.  NullPointerException (@PlayList:getDatabaseAlbum:386) {Thread-1204}

On Google Play the following:

java.lang.NullPointerException
    at es.hol.soundmedia.PlayList.getDatabaseAlbum(PlayList.java:386)
    at es.hol.soundmedia.PlayList.access$200(PlayList.java:31)
    at es.hol.soundmedia.PlayList$3.run(PlayList.java:458)
    at java.lang.Thread.run(Thread.java:856)

User Reports:

Android 4.1 3 75,0%
Hoje, 00:09 (APP 4.2.7) DROID RAZR i (smi) (PT-BR - dando erro quando escolhe musica)

Android 4.3 1 25,0%
2 de jun 11:31 (APP 4.2.4) Galaxy S3 (d2usc) Great application.

Beginning of the implementation is to get to the error:

    public void checkAll(final Group group, final Album album,
                         final List<Music> musics, final OnCheckListener callback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Handler handler = new Handler(Looper.getMainLooper());
                final Map<Integer,Boolean> map = new HashMap<Integer, Boolean>();
                Album _album = getDatabaseAlbum(group, album);
                if (!_album.hasValidId()) {
                    for (int index=0; index < musics.size(); index++)
                        map.put(index, false);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onCheckResult(map);
                        }
                    });
                    return;
                }
                for (int index=0; index < musics.size(); index++){
                    map.put(index, hasValidId(getDatabaseMusic(_album, musics.get(index))));
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCheckResult(map);
                    }
                });
            }
        }).start();
    }

Location of the error:

383    private Album getDatabaseAlbum(Group group, Album album){
384     QueryBuilder<Album, Integer> db = mAlbumDao.queryBuilder();
385     try {
386            Where<Album,Integer> where = db.where()
387                    .eq(Album.GROUP_ID_FIELD, group.getId()).and()
                    .eq(Album.ARTIST_FIELD, new SelectArg(album.getArtist())).and()
                    .eq(Album.URL_FIELD, new SelectArg(album.getUrl()));
            Album _album  = where.queryForFirst();

            if (hasValidId(_album))
                album = _album;
            else
                album.invalidateId();
        } catch (SQLException e) {
            Log.d(MainActivity.TAG, "Music", e);
            album.invalidateId();
        }
        return album;
    }

I see no other possibility besides 'queryBuilder'(var db) be returning null. Any idea why the error ?

384     QueryBuilder<Album, Integer> db = mAlbumDao.queryBuilder();
385     try {
386            Where<Album,Integer> where = db.where()

APP https://play.google.com/store/apps/details?id=es.hol.soundmedia

Refactoring model packages not updating DatabaseTableConfig

Hey,

I'm in the process of refactoring our model class package hierarchy and running into issues when upgrading to this new refactored version. It appears that DatabaseTableConfig stores the expected path to a given class, to be used when deserializing from the db. However, it doesn't appear to be updated after upgrades, at least not in my case.

My specific case is moving a class from com.company.services.path.Class to com.company.sdk.services.path.Class

Is there a way to trigger a recreation of this table? Ideally I would like to avoid having to manually modify the table. I haven't been able to find any good sources on how to do this.

Is there a way to create multiples tables based on one simple class?

I have a library project, with common functionalities and then i have multiple projects that depends on it.

Is there a way, for example, from one class "ArticleDTO" create multiple tables representing the categories that i have in each app?

Can i achieve this by using the table config file?

Failed tests on Windows

Looks like we have different \n at windows.

[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.j256.ormlite:ormlite-android:jar:4.49-SNAPSHOT
[WARNING] The expression ${version} is deprecated. Please use ${project.version} instead.
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building ORMLite Android 4.49-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-enforcer-plugin:1.0:enforce (enforce-maven) @ ormlite-android ---
[INFO]
[INFO] --- replacer:1.5.0:replace (validate) @ ormlite-android ---
[INFO] Replacement run on 1 file.
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ ormlite-android ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.1:compile (default-compile) @ ormlite-android ---
[INFO] Compiling 1 source file to O:\ormlite-android-master\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ ormlite-android ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory O:\ormlite-android-master\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.1:testCompile (default-testCompile) @ ormlite-android ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ ormlite-android ---
[INFO] Surefire report directory: O:\ormlite-android-master\target\surefire-reports


T E S T S

Running com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest
Wrote config for class com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foo
Done.
Wrote config for class com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foo
Done.
Wrote config for class com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$ForeignCollectionTest
Done.
Wrote config for class com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$ForeignCollectionTest
Wrote config for class com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foreign
Wrote config for class com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foo
Done.
Tests run: 4, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 0.211 sec <<< FAILURE!
testForeign(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest) Time elapsed: 0.111 sec <<< FAILURE!
java.lang.AssertionError: #

generated on 2014/09/22 11:30:57

--table-start--

dataClass=com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foo
tableName=foo

--table-fields-start--

--field-start--

fieldName=id
id=true

--field-end--

--field-start--

fieldName=foreign
foreign=true

--field-end--

--table-fields-end--

--table-end--

at org.junit.Assert.fail(Assert.java:91)
at org.junit.Assert.assertTrue(Assert.java:43)
at com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest.testForeign(OrmLiteConfigUtilTest.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

testBasic(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest) Time elapsed: 0.001 sec <<< FAILURE!
java.lang.AssertionError: #

generated on 2014/09/22 11:30:57

--table-start--

dataClass=com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foo
tableName=foo

--table-fields-start--

--field-start--

fieldName=id
id=true

--field-end--

--field-start--

fieldName=foreign
foreign=true

--field-end--

--table-fields-end--

--table-end--

at org.junit.Assert.fail(Assert.java:91)
at org.junit.Assert.assertTrue(Assert.java:43)
at com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest.testBasic(OrmLiteConfigUtilTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

testForeignCollection(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest) Time elapsed: 0.001 sec <<< FAILURE!
java.lang.AssertionError: #

generated on 2014/09/22 11:30:57

--table-start--

dataClass=com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$ForeignCollectionTest
tableName=foreigncollectiontest

--table-fields-start--

--field-start--

fieldName=collection
foreignCollection=true

--field-end--

--table-fields-end--

--table-end--

at org.junit.Assert.fail(Assert.java:91)
at org.junit.Assert.assertTrue(Assert.java:43)
at com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest.testForeignCollection(OrmLiteConfigUtilTest.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

testCurrentDir(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest) Time elapsed: 0.026 sec <<< FAILURE!
java.lang.AssertionError: #

generated on 2014/09/22 11:30:57

--table-start--

dataClass=com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$ForeignCollectionTest
tableName=foreigncollectiontest

--table-fields-start--

--field-start--

fieldName=collection
foreignCollection=true

--field-end--

--table-fields-end--

--table-end--

--table-start--

dataClass=com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foreign
tableName=foreign

--table-fields-start--

--field-start--

fieldName=id
id=true

--field-end--

--table-fields-end--

--table-end--

--table-start--

dataClass=com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest$Foo
tableName=foo

--table-fields-start--

--field-start--

fieldName=id
id=true

--field-end--

--field-start--

fieldName=foreign
foreign=true

--field-end--

--table-fields-end--

--table-end--

at org.junit.Assert.fail(Assert.java:91)
at org.junit.Assert.assertTrue(Assert.java:43)
at com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest.testCurrentDir(OrmLiteConfigUtilTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

Results :

Failed tests: testForeign(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest): #
(..)
testBasic(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest): #
(..)
testForeignCollection(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest): #
(..)
testCurrentDir(com.j256.ormlite.android.apptools.OrmLiteConfigUtilTest): #
(..)

Tests run: 4, Failures: 4, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.474 s
[INFO] Finished at: 2014-09-22T23:30:58+04:00
[INFO] Final Memory: 16M/98M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project ormlite-android: There are test failures.
[ERROR]
[ERROR] Please refer to O:\ormlite-android-master\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

defaultValue for boolean fields

From mattblang on SO: Neither defaultValue="1" nor defaultValue="true" seemed to work. I can set it using the setter before I create, but I was hoping to avoid this.

Android JOIN queries

I have a small problem with ORMLite JOIN queries on Android.

Category model

public class Category extends BaseModel {
    @DatabaseField(canBeNull = false, foreign = true)
    private Project project;

    @ForeignCollectionField(eager = false)
    private ForeignCollection<Criterion> criteria;

Criterion model

public class Criterion extends BaseModel  {
    @DatabaseField
    private boolean active;

    @DatabaseField
    private Integer weight;

    @DatabaseField(canBeNull = false, foreign = true)
    private Category category;

Relations:
Project has many categories (Category model)
Category has many criteria (Criterion model)
Project model is not important here so i skipped it.

My DAOs:

QueryBuilder<Criterion,Long> criteriaQueryBuilder = getCriterionDao().queryBuilder();
QueryBuilder<Category, Long> categoryQueryBuilder = getCategoryDao().queryBuilder();

I want to get categories and join all criteria, here is my query with JOIN:

// joined query
criteriaQueryBuilder.where().eq("active", Boolean.valueOf(true));

// my query with join
categoryQueryBuilder.
orderByRaw("id").
join(criteriaQueryBuilder). //add joined criteria
.prepareStatementString()

prepareStatementString() output:

SELECT `categories`.* FROM `categories` 
INNER JOIN `criteria` ON `categories`.`project_id` = `criteria`.`id`
WHERE `criteria`.`active` = 1
ORDER BY id 

I noticed that it joins criteria using wrong columns:

INNER JOIN `criteria` ON `categories`.`project_id` = `criteria`.`id`

Shouldn't output query look like this:

INNER JOIN `criteria` ON `categories`.`id` = `criteria`.`category_id`

Does ORMLite support it or I am doing something wrong here?

Best regards
Bart

Add ActionBarActivity

When I make a new project the default activity is an ActionBarActivity. However, to use OrmLite I have to change this to an OrmLite specific activity. Can an OrmLite activity be created that inherits from ActionBarActivity?

I've currently copied and pasted the OrmLiteBaseActivity code into a new class that extends ActionBarActivity as a workaround.

Programmatic API to generate a config file

Hi @j256 ,

I could work on the gradle plugin for Android :
https://github.com/stephanenicolas/ormlite-android-gradle-plugin

Currently the plugin is still immature. But it can work for most apps I think. It still needs more configuration and more adaptation to the gradle life cycle for android.

Nevertheless, it works only by using command line to drive the OrmLiteConfigUtil class. It was really the simplest way to do it. But a real API would be so much better !

https://github.com/j256/ormlite-android/blob/master/src/main/java/com/j256/ormlite/android/apptools/OrmLiteConfigUtil.java

Here are some concerns with this class :

  • every method is static, it doesn't allow extension by inheritance
  • most methods are static and you need to extend the class to use them
    For this, it would be nice to have a simpler standard java class with public, protected and private methods.

Also, the class :

  • is not customizable enough, it does too many things by itself and should not assume any project structure, like trying to find both java source files and the raw folder from a common root, then also loading the classes into memory from jar files, etc..
  • for gradle we need to pass you :
    ** one or more folders that contains sources
    ** a destinationDir to write to
    ** the name of the config file in it
    ** glups, the hard part ! : the classpath

we need to feed you with a classpath because you load the classes and use them. (This problem would not be present with an annotation problem, but annotation processors have also their disadvantages.)

Also, we need to configure the classpath as with gradle, different classpaths can be defined for different flavors.

But then, we will run into a new problem (I know because I tried) : the annotation classes used in ormlite source code, will not be the same as the annotations classes used in the source code of the app. And ORM Lite is not able to recognize those annotations because they live in a different class loader.

Ways to workaround this would be

  1. share the classpath as you currently do : the utility app must have the classes to manipulate in its classpath. But that is harder to do programmatically, and may also look a bit awkward : the class loader being used as a kind of class storage shared by the app and the plugin
  2. make it possible to recognize annotations not by classes but by names.

Solution 2 is the most clean but can be tricky on the performance level. Maybe with a strategy pattern it can be smoothened. Solution 1 is a bit awkward, but can be the simplest for developers.

And this can be largely worked around with an annotation processor, but it also comes with some complexity, but probably the best way to do it.

Android's Cursor did not implement Closeable until API Level 16, causes Exception

According to https://developer.android.com/sdk/api_diff/16/changes/android.database.Cursor.html , the Closeable interface was not added until API Level 16.

So the change in 28500b3 causes a runtime exception:

java.lang.IncompatibleClassChangeError: interface not implemented
        at com.j256.ormlite.misc.IOUtils.closeQuietly(IOUtils.java:20)
        at com.j256.ormlite.android.AndroidDatabaseConnection.queryForLong(AndroidDatabaseConnection.java:247)
        at com.j256.ormlite.stmt.StatementExecutor.ifExists(StatementExecutor.java:647)

I discovered this running the ormlite-android from the current master on an Android 4.0.4 phone.

Caused by: java.lang.IllegalArgumentException: Could not find appropriate get method for private XXX.id

Hi,

I am encountering this exception which i don't understand.

Caused by: java.lang.IllegalArgumentException: Could not find appropriate get method for private 
java.lang.String com.xx.xx.xx.json.XXX.id

In my XXX pojo, getId method was defined, so i don't understand why this happens, anyone could shed some light on it?

    @DatabaseField(columnName = Table.Columns.ID, id = true, useGetSet = true, unique = true)
    private String id;

    public String getId() {
        return aggregateStart.getTime() + "-" + aggregateEnd.getTime() + "-" + aggregateInterval;
    }

    public void setId(final String id) {
        this.id = id;
    }

is id not allowed as String instead of int? or getId cannot return concatenated string?
Thanks!

Replace multiple SELECT with INNER JOIN

Hi! I faced problem, that ormLite using multiple select instead inner join for foreign fields, and it highly slow down working with database.
Is there way to use foreignAutoRefresh = true, maxForeignAutoRefreshLevel = 1 with inner join?

Better integrated OrmLiteConfigUtil

The way the class OrmLiteConfigUtil is working is quite hacky, it requires both the source code and the class files.

There are better alternatives nowadays:

  • It can be implemented as a standard annotation processor, taking the class files as input.
  • It can be implemented very easily as a Java source parser, using the QDox library, taking the java source file as input.

The later solution is pretty useful for the Android : it doesn't require to compile the files first and can be easily integrated into a Gradle build (i.e. this can be implemented as a task executed before the app's resources are processed by the Android plugin, far before the compilation of the source code takes place).

I am willing to implement the second solution as a contribution to the project. Are you going to integrate it to the project?

Join problem with query

I'm doing some join tests and i'm having a join getting the wrong column

Here are my models:

public class PontoVenda extends BaseModel {
@DatabaseField(canBeNull = false)
private Integer codigo;
@DatabaseField(canBeNull = false)
private String razao;
@DatabaseField(canBeNull = false)
private String nome;
@DatabaseField(canBeNull = false)
private String endereco;
@DatabaseField
private String cep;
@DatabaseField(canBeNull = false, foreign = true)
private Cdd cdd;
@DatabaseField(canBeNull = true, foreign = true)
private Bairro bairro;
@DatabaseField(canBeNull = true, foreign = true)
private Municipio municipio;
}

public class Cdd extends BaseModel {
@DatabaseField(canBeNull = false)
private String descricao;
@DatabaseField(canBeNull = false)
private String uuid;
@DatabaseField(canBeNull = false)
private Integer unb;
@DatabaseField(canBeNull = false, foreign = true)
private Geo geo;
}

My queryBuilder joins:

QueryBuilder<PontoVenda, ?> pdvQb =       DaoManager.createDao(getPdvRepository().getDB().getConnectionSource(),
            PontoVenda.class).queryBuilder();
    QueryBuilder<Cdd, ?> cddQb = DaoManager.createDao(getPdvRepository().getDB().getConnectionSource(),
            Cdd.class).queryBuilder();

This is the sql output from the prepareStatementString

﹕ SELECT pontovenda.* FROM pontovenda INNER JOIN cdd ON pontovenda.bairro_id = cdd.id

Why is he joining a column that does not relate with the Cdd class at all? Am im doing something wrong?

Thank you,

Exception:queryForLong from database failed

I had a BaseHelper which extends OrmLiteSqliteOpenHelper,and create the table Test.class.But,when I add the data,it throw the exception 'queryForLong from database failed: SELECT COUNT(*) FROM tb_test111 WHERE id = ?'

Can not access database with Ormlite

there is i did

Experiment 1:

     ```
    su
    chmod 777 /data/data/not.my.app/databases
    chmod 666 /data/data/not.my.app/databases/data.db
    ```

then i use ormlite to access it ,OK,it work,but that app can't access this .db anymore . I rechanged the permission ,still can't work .By the way,that app->"not.my.app" used ormlite too.

Experiment 2:

I copy data.db file to my app's databases folder and chown and chmod ,still not work .SQLException throw :Getting a writable database from helper DBHelper failed.

so i dont konw it's a bug or the way i used is wrong.

CursorLoader and Support Library

Hey,

Once there were support versions for apptools.OrmLiteCursorAdapter and apptools.OrmLiteCursorLoader located in apptools.support but they seem to have been removed. Whats the reason for this?

This makes it really hard to implement CursorAdapters below Api v11 without fiddling around cursors.

SimpleDateFormat doesn't read MS correctly in Android 5.0 and zeros milliseconds for date fields

In my project I have noticed that when writing date fields the second fractions are written as a string that ends in .000321 for Android 4.x devices. This is when writing a java.util.Date field, so only goes to MS accuracy. Uses default ORMLite date formatter.

On Android 5 however, the dates are written as .321000. This is with the same version of ORMLite (4.48) and both targeting Android SDK 19.

From what I have read the yyyy-MM-dd HH:mm:ss.SSSSSS format that ORMLite uses as default for dates behaves differently for milliseconds on Android 5.0.

Obviously this now breaks compatibility for my users that has upgraded to Android 5.0 (at least all the MS fields now revert to zero, this breaks a unique constraint on my data on an update, for rows created in same second.) The only workaround that I can think of is to change all the date formats for my fields to be SSS second fractions, and upgrade my db to string replace all my date fields that contain .000 with . (Fields that are already saved as .321000 (and passed constraints) will still read correctly, so should need no update.)

Android app using LocalLog instead of Logcat

I just figured out that the android app I work for was using LocalLog instead of Logcat. (https://nimbledroid.com/play/com.groupon#logger.LocalLog%20static%20initializer)

After debugging a bit I noticed that com.j256.ormlite.android.AndroidLog was getting removed from the APK by Proguard.
To fix this I modified our proguard.cfg with:

-keep class com.j256.ormlite.android.AndroidLog { *; }

I also added:

System.setProperty(LoggerFactory.LOG_TYPE_SYSTEM_PROPERTY, "ANDROID");

To my Application code. When AndroidLog is not available, you will see a log statement like this:

System.out(13038): 2016-02-13 15:51:08,360 [WARNING] StatementExecutor Unable to call constructor with single String argument for class com.j256.ormlite.android.AndroidLog, so had to use local log: com.j256.ormlite.android.AndroidLog

@j256 it might be interesting mentioning this in the Logging section of the docs.

SELECT DISTINCT CASE

When running this query:
SELECT DISTINCT (CASE WHEN senderId = 3851 THEN recipientId ELSE senderId END) , * FROMmessage WHERE (senderId= 3851 ORrecipientId= 3851 ) GROUP BY CASE WHEN senderId = 3851 THEN recipientId ELSE senderId END ORDER BY CASE WHEN senderId = 3851 THEN recipientId ELSE senderId END, datetime(dateTime) DESC

Error occurs:
java.lang.IllegalArgumentException: Unknown column name '(CASE WHEN senderId = 3851 THEN recipientId ELSE senderId END)' in table message

As far as I am aware query is fine and sqlite can manage distinction and cases.
*The code i am running: *

`String orderCase = "CASE WHEN " + Message.SENDER_ID + " = " + userId +
                        " THEN " + Message.RECIPIENT_ID + " ELSE " + Message.SENDER_ID + " END";
                Dao<Message, Long> dao = getDao(Message.class);
                QueryBuilder<Message, Long> queryBuilder = dao.queryBuilder();
                queryBuilder.distinct().selectRaw(orderCase + ", *");
                Where<Message, Long> where = queryBuilder.where();
                where.or(
                        where.eq(Message.SENDER_ID, userId),
                        where.eq(Message.RECIPIENT_ID, userId));
                queryBuilder.setWhere(where);
                queryBuilder
                        .groupByRaw(orderCase)
                        .orderByRaw(orderCase + ", datetime(" + Message.DATE_TIME + ") DESC");

                Log.e(TAG, "Query: " + queryBuilder.prepareStatementString());
                GenericRawResults<Message> rawResults = dao.queryRaw(
                        queryBuilder.prepareStatementString(), dao.getRawRowMapper());
                try {
                    return rawResults.getResults();
                    //return queryBuilder.query();
                } finally {
                    rawResults.close();
                }`

Is this a bug?

cannot rollback - no transaction is active (code 1) in RuntimeExceptionDao#callBatchTasks

The following exception has been encountered:

android.database.sqlite.SQLiteException: cannot rollback - no transaction is active (code 1)
    at android.database.sqlite.SQLiteConnection.nativeExecute(Native Method)
    at android.database.sqlite.SQLiteConnection.execute(SQLiteConnection.java:679)
    at android.database.sqlite.SQLiteSession.endTransactionUnchecked(SQLiteSession.java:439)
    at android.database.sqlite.SQLiteSession.endTransaction(SQLiteSession.java:401)
    at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:522)
    at com.j256.ormlite.android.AndroidDatabaseConnection.setAutoCommit(SourceFile:77)
    at com.j256.ormlite.misc.TransactionManager.callInTransaction(SourceFile:197)
    at com.j256.ormlite.stmt.StatementExecutor.callBatchTasks(SourceFile:553)
    at com.j256.ormlite.dao.BaseDaoImpl.callBatchTasks(SourceFile:633)
    at com.j256.ormlite.dao.RuntimeExceptionDao.callBatchTasks(SourceFile:534)

ormlite-android:4.48
ormlite-core:4.48
Android: 4.1.2
Only DB operations in Callable are createOrUpdate.

Generate Table Config File at First Run

Hello,

I noticed that currently we have to create a Table Config File before launching the App and we have to update it everytime a change is made in the tables, as explained in the ORMLite Documentation.

The process isn't very programmer-friendly because is tedious and programmers love everything that works out of the box, so I thought of a way to get rid of the process by doing it automatically the first time the App is run.

Why? Because:

  • No need to re-run another program everytime a change is made to the model (process the developer may forget)
  • As the writeConfigFile() is run at the first run, it will process the tables currently in code, so the developer(s) can change the model without problems
  • The process at startup may be slow, but it will run once, so it won't disturb the user the next times the App is run

This could be an additional option, maybe something like:

private DBHelper getHelper() {
    if (databaseHelper == null) {
        boolean shouldWriteConfigFileAtStartup = true;
        databaseHelper =
            OpenHelperManager.getHelper(this, DatabaseHelper.class, shouldWriteConfigFileAtStartup);
    }
    return databaseHelper;
}

I hope this helps to make ORMLite even better 😃

Out-of-nowhere ClassCastException

Hi,

This morning I woke up on this strange exception:

java.lang.ClassCastException: org.apache.harmony.luni.lang.reflect.ImplForVariable cannot be cast to java.lang.Class

It happens when I try to create any table with a Collection of foreign objects.

Example:

Call to create table:
TableUtils.createTableIfNotExists(databaseHelper.getConnectionSource(), DisplayedShopItem.class);

Class object:

@databasetable(tableName = "displayed_shop_item")
public class DisplayedShopItem {

[...]

@ForeignCollectionField(eager = true)
private Collection<CategoryDisplayedShopItem> categories;

[...]

public Collection<CategoryDisplayedShopItem> getCategories() {
    return categories;
}

public void setCategories(Collection<CategoryDisplayedShopItem> categories) {
    this.categories = categories;
}

[...]
}

The class that is said to be an ImplForVariable (??):

@databasetable(tableName = "category_displayed_shop_item")
public class CategoryDisplayedShopItem {

@DatabaseField(foreign = true, foreignAutoRefresh = true)
private Category category;

@DatabaseField(foreign = true)
private DisplayedShopItem shopItem;

public CategoryDisplayedShopItem() {

}

public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}

public DisplayedShopItem getShopItem() {
    return shopItem;
}

public void setShopItem(DisplayedShopItem shopItem) {
    this.shopItem = shopItem;
}

}

The trace says the error is at :

com.j256.ormlite.field.FieldType.configDaoInformation(FieldType.java:370)

which is:

Class collectionClazz = (Class) genericArguments[0];

This has been working for weeks, and now it fails without even touching it.

I am totally lost right now...

Thanks.

Update by multi-thread

Hi all,

I came across a weird issue while updating a table by multi threads.
Each thread fetches data from web service and create/update it into the table - callBatchTasks is used.
if 2 or 3 threads update rows (around 50), no problem. if 14 threads update total 200 rows simultaneously, sometimes, in a random way, some rows are deleted. I found there is no delete api explicitly.

db before
1 a
2 b
3 c
4 d
5 f

db after
1 a
2 b
5 f

the createOrUpdate api returns successful for all 5 rows but where are 2 rows?
I'm not sure if I miss something or this is a bug? Thanks in advance.

Thanks,
Daniel

String with escaped quote causing failure in SQL

https://play.google.com/store/apps/details?id=es.hol.soundmedia

'What\'s Up'

This string was added to the database, but when searching for it, several exceptions are thrown.
It is clear that the problem was caused by escaped quote, but how to solve using the orm?

11-10 15:43:51.704  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.704  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.719  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.719  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.729  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.729  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.744  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.744  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.759  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.759  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.769  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.769  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.779  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.779  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.794  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.794  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.804  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error
11-10 15:43:51.804  23612-23612/es.hol.soundmedia E/es.hol.soundmedia.main﹕ Problems executing Android query: SELECT * FROM `MUSIC` WHERE ((`ALBUM_ID` = 24 AND `ARTIST` = 'GOOD TIMES' ) AND `TITLE` = 'What\'s Up' )
11-10 15:43:51.814  23612-23612/es.hol.soundmedia E/SQLiteLog﹕ (1) near "s": syntax error````

Thank you.

Cursor window allocation of 2048 kb failed.

Fatal Exception: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
at android.database.CursorWindow.(CursorWindow.java)
at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java)
at android.database.AbstractCursor.moveToPosition(AbstractCursor.java)
at android.database.AbstractCursor.moveToFirst(AbstractCursor.java)
at com.j256.ormlite.android.AndroidCompiledStatement.getCursor(AndroidCompiledStatement.java)
at com.j256.ormlite.android.AndroidCompiledStatement.runQuery(AndroidCompiledStatement.java)
at com.j256.ormlite.stmt.SelectIterator.(SelectIterator.java)
at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java)
at com.j256.ormlite.dao.BaseDaoImpl.createIterator(BaseDaoImpl.java)
at com.j256.ormlite.dao.BaseDaoImpl.iterator(BaseDaoImpl.java)
at com.j256.ormlite.dao.LazyForeignCollection.seperateIteratorThrow(LazyForeignCollection.java)
at com.j256.ormlite.dao.LazyForeignCollection.iteratorThrow(LazyForeignCollection.java)
at com.j256.ormlite.dao.LazyForeignCollection.closeableIterator(LazyForeignCollection.java)
at com.j256.ormlite.dao.LazyForeignCollection.iterator(LazyForeignCollection.java)
at com.j256.ormlite.dao.LazyForeignCollection.iterator(LazyForeignCollection.java)

java.lang.NoClassDefFoundError: rx.schedulers.Schedulers

compile 'com.j256.ormlite:ormlite-android:4.48'
compile 'com.j256.ormlite:ormlite-core:4.48'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'

For a strange cause, I am getting "java.lang.NoClassDefFoundError: rx.schedulers.Schedulers" when I try to compile in a device with Android 4.4.4, api 19 and ORMLite.
I don't have such problem without ORMLite nor in device with api 23.

Some one know why my "reactive package" is bing excluded from my apk ?

Wrote Complete: Support Multi-DB within OpenHelperManager. Need PR?

Hi! I'm a Ormlite fan. We have many projects that use your products. Thanks a million!

Note: My English is not good. So I would speak as briefly as possible and use simple words.

Before

We used to refer your example HelloAndroidTwoDbs to suppport multi-db.

In addition, lacking any better idea :-(

After

Later, I tried to modify OpenHelerManager.

I created two new classes: OpenHelper and OpenHelpers. The role of OpenHelper is almost the same as the original OpenHelperManager, except became into a instance. OpenHelpers is used to manage all of the OpenHelper.

Just like:

Dao<City, Long> dao = OpenHelpers.getDao(context, CityHelper.class, City.class);
OpenHelpers.release(CityHelper.class);

These OrmLiteSqliteOpenHelper(s) match the ones all over the New OpenHelper(s). Fully comply with the rules!

Other usage:

CityHelper helper = OpenHelpers.getOrmliteHelper(context, CityHelper.class);
OpenHelper openHelper = OpenHelpers.get(CityHelper.class);

Advantage

It's very fruitful. These classes has approached the issue in a practical way. You won't need to reference any example, rewrite any extra code. Just need to use that one.

Testing

I wrote some simple unit-test code, have long time for our project.
All operators have to verify is passed, ease of use!

Ending

If @j256 want to use these code, please tell me. I will improve the unit test, and PR to your project.

Awaiting for your reply.
Thank you very much!

CC: @VincentFTS @emmby

Maven build error

Thanks for this awesome library. It makes working on database much more easier and time saving. I am new to Maven build and while doing mvn compile, I get following errors

 Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project com.j256.ormlite:ormlite-android:jar:4.49-SNAPSHOT: The following artifacts could not be resolved: com.j256.ormlite:ormlite-core:jar:4.49-SNAPSHOT, com.j256.ormlite:ormlite-core:jar:tests:4.49-SNAPSHOT: Failure to find com.j256.ormlite:ormlite-core:jar:4.49-SNAPSHOT in https://oss.sonatype.org/content/repositories/snapshots was cached in the local repository, resolution will not be reattempted until the update interval of sonatype-nexus-snapshots has elapsed or updates are forced

I have successfully built, ormlite-core. Is there anyway, I can modify ormlite-android pom.xml, so that I can use local ormlite-core jar file. Thanks

ConfigUtil doesn't show error message when "res/raw" folder doesn't exist

Hello again,

I tried a month ago to run the OrmLiteConfigUtil but it never wrote the config file. I thought there was some bug in Eclipse/Android SDK/Java so I decided to forget about it.

Today I re-read the documentation and noticed the "res/raw" folder should exist so the util can run. Well, it would be very nice if an error message is printed when the "res/raw" folder isn't created yet.

I hope this helps.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.