[英]Database conflicts between threads
My application parses three different XML's and saves them to database. 我的应用程序解析了三种不同的XML,并将它们保存到数据库中。 It worked fine as long as I used AsyncTask, with progress dialog, because all of them were executed one after another.
只要我将AsyncTask与进度对话框配合使用,它就可以正常工作,因为它们都一个接一个地执行。 I'm now starting to parse that data simultaneously in three different threads (+UI thread).
我现在开始在三个不同的线程(+ UI线程)中同时解析该数据。 Now these four threads fight for database, and sometimes crash, always if UI thread is being used.
现在,这四个线程争用数据库,有时如果使用UI线程,则有时会崩溃。 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: 每次插入数据时,我都会使用此方法和类似方法插入大约80个项目:
public void addDBSplosna(SplosnaRazred s) {
db.open();
db.insertSplosna(s);
db.close();
}
DBAdapter: 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?
如果是这样,该怎么办?
您可以使方法addDBSplosna(SplosnaRazred s) 同步 ,以确保当时只有一个线程可以写入数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.