My application parses three different XML’s and saves them to database. It worked fine as long as I used AsyncTask, with progress dialog, because all of them were executed one after another. I’m now starting to parse that data simultaneously in three different threads (+UI thread). Now these four threads fight for database, and sometimes crash, always if UI thread is being used. I get the following errors:
ERROR/AndroidRuntime(651): Caused by: java.lang.IllegalStateException: database /data/data/edu.activity/databases/vreme already closed
then another time i get
INFO/System.out(667): XML Pasing5 Excpetion = java.lang.IllegalStateException: database not open
or this one
01-30 00:56:05.232: ERROR/AndroidRuntime(731): FATAL EXCEPTION: Thread-11
01-30 00:56:05.232: ERROR/AndroidRuntime(731): java.lang.IllegalStateException: database not open
01-30 00:56:05.232: ERROR/AndroidRuntime(731): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1493)
01-30 00:56:05.232: ERROR/AndroidRuntime(731): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
01-30 00:56:05.232: ERROR/AndroidRuntime(731): at edu.database.DBAdapter.insertSamodejne(DBAdapter.java:229)
01-30 00:56:05.232: ERROR/AndroidRuntime(731): at edu.util.ApplicationInt.addDBSamodejne(ApplicationInt.java:49)
01-30 00:56:05.232: ERROR/AndroidRuntime(731): at edu.xml.XMLtoDB.insertSamodejne(XMLtoDB.java:58)
01-30 00:56:05.232: ERROR/AndroidRuntime(731): at edu.activity.SplashScreen$4.run(SplashScreen.java:97)
01-30 00:56:05.232: ERROR/AndroidRuntime(731): at java.lang.Thread.run(Thread.java:1096)
I insert about 80 items every time I insert data, using this and similar methods:
public void addDBSplosna(SplosnaRazred s) {
db.open();
db.insertSplosna(s);
db.close();
}
DBAdapter:
public long insertSplosna(SplosnaRazred splosna) {
ContentValues initialValues = new ContentValues();
initialValues.put(VREMENSKA, splosna.getVremenska());
initialValues.put(OBETI, splosna.getObeti());
initialValues.put(UPDATED, splosna.getServerUpdated());
return db.insert(TABLE_SPLOS, null, initialValues);
}
Is there a way to stop them from fighting for database? Should I lock the database until it’s done and then release it? If that’s the case, how to do it?
you can make method addDBSplosna(SplosnaRazred s) synchronized, to be sure that only one thread at the time can write to DB.