Android多个数据库打开

我正在为Android的即时通讯客户端,我正在与数据库存储联系人和其他信息…在我的应用程序,我有一个活动和一个服务。 我需要在服务和活动上同时打开三个数据库。

我使用三个数据库,因为我想要更容易地pipe理数据库,而不会有写入同步的问题。 (据我所知,我需要同步写入数据库,因为它可能会粉碎)。

为了同时pipe理服务和活动的数据库,我认为单身或者静态类的DatabaseHelper可以帮助我…

所以我已经开始通过在活动中创build两个数据库帮助器全局对象来进行testing,每一个在运行项目之后打开一个不同的数据库,我注意到最后打开的数据库在这两个对象中都保持打开:((为什么是这个发生了什么?

有人可以让我怎么做这个工作? 谢谢!

LE:经过更多的testing,我做了一个数据库帮助器的Static对象,打开一个服务,从中取出数据库对象的活动,同时我做了两个for语句,一个在活动中,一个在服务中运行,从0到3000并将一些值添加到同一个数据库中,然后读取数据库。

在这个运行后,我注意到数据库仍然在脚下,运行没有错误。 奇怪的是服务只在活动完成后才运行。 这是为什么? 谢谢!

我有一个DatabaseAdapter类,它包含两个数据库一起打开。

public class DatabaseAdapter { /** Identifier for the internal database */ public static final int INTERNAL = 0; /** Identifier for the external database */ public static final int EXTERNAL = 1; private final SQLiteOpenHelper[] mDatabaseManager = new SQLiteOpenHelper[2]; private final SQLiteDatabase[] mDatabases = new SQLiteDatabase[2]; /** * Constructs the database and open it. */ public DatabaseAdapter() { // Open the internal_db mDatabaseManager[INTERNAL] = new InternalDatabaseManager(MyApplication.getInstance()); mDatabases[INTERNAL] = mDatabaseManager[INTERNAL].getWritableDatabase(); } /** * Checks the database state and throws an {@link IllegalStateException} if database isn't open. * Should always be used before starting to access the database. * * @param type Type of the database. Can be INTERNAL or EXTERNAL. */ public void checkDbState(int type) { if (mDatabases[type] == null || !mDatabases[type].isOpen()) { throw new IllegalStateException("The database has not been opened"); } } /** * Closes the database of the given type. * * @param type Type of the database. Can be INTERNAL or EXTERNAL. */ public void close(int type) { if (mDatabases[type].isOpen()) { mDatabases[type].close(); mDatabases[type] = null; if (mDatabaseManager[type] != null) { mDatabaseManager[type].close(); mDatabaseManager[type] = null; } } } /** * @param type Type of the database. Can be INTERNAL or EXTERNAL. * @return true if the database is open, false otherwise. */ public boolean isOpen(int type) { return mDatabases[type] != null && mDatabases[type].isOpen(); } /** * Opens the default database. * * @param type Type of the database. Can be INTERNAL or EXTERNAL. */ public void open(int type) { switch (type) { case INTERNAL: mDatabaseManager[INTERNAL] = new InternalDatabaseManager(MyApplication.getInstance()); if (!isOpen(INTERNAL)) { mDatabases[INTERNAL] = mDatabaseManager[INTERNAL].getWritableDatabase(); } break; case EXTERNAL: mDatabaseManager[EXTERNAL] = new ExternalDatabaseManager(MyApplication.getInstance(), Constants.EXTERNAL_DB_PATH, 1); if (!isOpen(EXTERNAL)) { mDatabases[EXTERNAL] = mDatabaseManager[EXTERNAL].getWritableDatabase(); } break; } } } 

添加第三个应该很容易:)