2011-11-11 44 views
0

我正在使用一個DBManager層,它保存爲私有成員所有表的SQLiteOpenHelpers。該類作爲跟隨DBManager在Android應用程序

public class DBManager 
{ 
    private static final String mTAG = "DBManager"; 
    Context      mContext    = null; 
    DB1   mDB1  = null; 
    DB2   mDB2  = null; 

    public DBManager(Context context) 
    { 
     mContext = context; 

     mDB1 = new DB1(mContext); 
     mDB2 = new DB2(mContext); 
    } 

    @Override 
    protected void finalize() throws Throwable 
    { 
     Close(); 

     super.finalize(); 
    } 

    public void Close() 
    { 
     if(mDB1 != null) mDB1.close(); 
     if(mDB2 != null) mDB2.close(); 
    } 

    .... Public API towards the DB1/DB2.... 

}

的問題是這樣的: 目前,我在每一個活動,我需要的DB作爲私有成員使用。 也許更好地使用它作爲單身人士?我可以嗎?如果是 - 要傳遞哪個上下文? 或其他任何使用方式?

謝謝

回答

0

這就是我所做的。每個數據庫保存一個SqliteOpenHelper實例。不要爲單個數據庫保留多個助手。如果多個線程同時嘗試寫入,這可能會導致寫入問題。

將Helper實例作爲單例存放在您的應用程序進程中。多個活動和服務客戶​​端可以輕鬆訪問它,並且您不會遇到寫入鎖定問題。

看到這裏的細節:

http://www.touchlab.co/blog/single-sqlite-connection/

它鏈接到有關SQLite和多個連接我的幾篇博客。