4

I am using ormLite to store data on device. I can not understand why but when I store about 100 objects some of them stores too long time, up to second. Here is the code

from DatabaseManager:

public class DatabaseManager 
    public void addSomeObject(SomeObject object) {
        try {
            getHelper().getSomeObjectDao().create(object);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public class DatabaseHelper extends OrmLiteSqliteOpenHelper

    public Dao<SomeObject, Integer> getSomeObjectDao() {
        if (null == someObjectDao) {
            try {
                someObjectDao = getDao(SomeObject.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return someObjectDao;
    }

Any ideas to avoid this situations?

Gray
  • 115,027
  • 24
  • 293
  • 354
Aleksandr
  • 787
  • 6
  • 22
  • So you say it takes a second to insert 100 objects? Or that some of them each take a second? – Gray May 25 '13 at 14:59
  • Possible duplicate of http://stackoverflow.com/questions/11761472/ormlites-createorupdate-seems-slow-what-is-normal-speed – Gray May 25 '13 at 15:00
  • no, most items saves in 10-20-30 millis, but few (3-5 pcs) in 300-1000 ms. – Aleksandr May 25 '13 at 18:08
  • The DAO creation is the most expensive bit so the 1st one might take a lot more time than the others. But unless there is some difference in the data, I can't explain why a couple entries out of a 100 lake 10 times longer. – Gray May 25 '13 at 18:28
  • I guess this is not right way but currently I solved the problem by extracting this action to separate thread. I tryed few times with the same data sets and every time it was different objects, so it does not depends of objects. – Aleksandr May 25 '13 at 19:32

1 Answers1

11

Thanks to Gray! Solution is, as mentioned Gray, using callBatchTasks method:

public void updateListOfObjects (final List <Object> list) {
    try {
        getHelper().getObjectDao().callBatchTasks(new Callable<Object> (){
        @Override
        public Object call() throws Exception {
            for (Object obj : list){
                getHelper().getObjectDao().createOrUpdate(obj);
                }
            return null;
        }

    });
} catch (Exception e) {
    Log.d(TAG, "updateListOfObjects. Exception " + e.toString());
}
}

Using this way, my objects (two types of objects, 1st type - about 100 items, 2nd type - about 150 items) store in 1.7 sec.

See the ORMLite documentation.

Gray
  • 115,027
  • 24
  • 293
  • 354
Aleksandr
  • 787
  • 6
  • 22