简体   繁体   中英

Database conflicts between threads

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?

您可以使方法addDBSplosna(SplosnaRazred s) 同步 ,以确保当时只有一个线程可以写入数据库。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM