简体   繁体   English

打开和关闭SqliteDatabase

[英]opening and closing SqliteDatabase

I'm moving from java to android development. 我正在从Java转向android开发。 Previously I worked on Hybernates in java. 以前,我在Java中研究Hybernates。 So android sqlite database handling is bit confusing me. 因此,Android sqlite数据库处理让我有些困惑。 I'm using a singleton database helper class and created methods for opening and closing daabase inside my helper class itself like as follows... 我正在使用一个单例数据库助手类,并在我的助手类本身内部创建了用于打开和关闭daabase的方法,如下所示...

public class DatabaseManager extends SQLiteOpenHelper {
 private static DatabaseManager instance;
 public static DatabaseManager getInstance(Context context) {
    if (instance == null)
        instance = new DatabaseManager(context);
    return instance;
}
public static DatabaseManager getInstance() {
    return instance;
}
 @Override
public void onCreate(SQLiteDatabase db) {
    //CREATING TABLES...
}
 public SQLiteDatabase getReadableDatabase(String logMsg) {
    Log.d(TAG, "Readable database opening from :" + logMsg);
    return super.getReadableDatabase();
}

public SQLiteDatabase getWritableDatabase(String logMsg) {
    Log.d(TAG, "Writable database opening from :" + logMsg);
    return super.getWritableDatabase();
}

public void closeDb(SQLiteDatabase db, String logMsg) {
    db.close();
    Log.d(TAG, "Closing db from :" + logMsg);
}
}

Now my situation I'm working on a messaging application. 现在,我正在研究消息传递应用程序。 In that there will be some listeners running back, they insert/retrieve data inside one of those tables of application's db. 由于会有一些监听器在运行,它们将数据插入/检索应用程序数据库的那些表之一。 And I'm planning in my activity to use a content provider to load listview with ResourceCursorAdapter from messages table. 我计划在活动中使用内容提供程序从消息表中加载带有ResourceCursorAdapter listview。 If I open and close database during background and in activity(onResume,onPause) will it cause in problems? 如果我在后台和活动期间(onResume,onPause)打开和关闭数据库,是否会引起问题? If this is not the right approach how should i handle this situation? 如果这不是正确的方法,我应该如何处理这种情况? Thanks in advance.... 提前致谢....

It's best not to keep the database open for too long. 最好不要将数据库打开太长时间。 As many of the lifecycle events may or may not occur, it's best to just open the database when needed, do all the operations in the database and close immediately. 由于许多生命周期事件可能会或可能不会发生,因此最好仅在需要时打开数据库,执行数据库中的所有操作并立即关闭。

Therefore you don't really need the 3 last methods in your class unless you're planning to use them to centralise some other operations (like you did with logging). 因此,除非您打算使用它们来集中其他一些操作(例如与日志记录一样),否则您实际上并不需要类中的最后3个方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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