解决多线程并发访问SQLite数据库

来源:互联网 发布:js代码解压缩工具 编辑:程序博客网 时间:2024/05/21 12:08

   java.lang.IllegalStateException: attempt to re-open an already-closed object

       使用单例实现:如下

  1. import android.database.sqlite.SQLiteDatabase;  
  2. import android.database.sqlite.SQLiteOpenHelper;  
  3. import java.util.concurrent.atomic.AtomicInteger;  
  4. /**  
  5.  *多线程下调用SQLite  
  6.  *   
  7.  * @author daniel  
  8.  *   
  9.  */  
  10. public class DBManager {  
  11.     //解决多线程并发  
  12.     private AtomicInteger mOpenCounter = new AtomicInteger();  
  13.     private static DBManager instance;  
  14.     private static SQLiteOpenHelper mDatabaseHelper;  
  15.     private SQLiteDatabase mDatabase;  
  16.     private DBManager(){  
  17.           
  18.     }  
  19.   
  20.     /**  
  21.      * 初始化  
  22.      * @param helper  
  23.      */  
  24.     public static synchronized void initializeInstance(SQLiteOpenHelper helper) {  
  25.         if (instance == null) {  
  26.             instance = new DBManager();  
  27.             mDatabaseHelper = helper;  
  28.         }  
  29.     }  
  30.   
  31.     /**  
  32.      * 获得当前实例对象  
  33.      * @return  
  34.      */  
  35.     public static synchronized DBManager getInstance() {  
  36.         if (instance == null) {  
  37.             throw new IllegalStateException(  
  38.                     DBManager.class.getSimpleName()  
  39.                             + " is not initialized, call initializeInstance(..) method first.");  
  40.         }  
  41.   
  42.         return instance;  
  43.     }  
  44.   
  45.     /**  
  46.      * 打开数据库对象   
  47.      * @return  
  48.      */  
  49.     public synchronized SQLiteDatabase openDatabase() {  
  50.         if (mOpenCounter.incrementAndGet() == 1) {  
  51.             // Opening new database  
  52.             mDatabase = mDatabaseHelper.getWritableDatabase();  
  53.         }  
  54.         return mDatabase;  
  55.     }  
  56.     /**  
  57.      * 多线程下关闭  
  58.      */  
  59.     public synchronized void closeDatabase() {  
  60.         if (mOpenCounter.decrementAndGet() == 0) {  
  61.             // Closing database  
  62.             mDatabase.close();  
  63.   
  64.         }  
  65.     }  


    转载自http://blog.csdn.net/dingsai88/article/details/41676373

原创粉丝点击