如何在这么多片段中管理数据库打开关闭

时间:2014-08-25 13:37:11

标签: android android-fragments

我正在使用一个应用程序,因为有很多片段所有片段都在使用数据库,我只是想知道如何在这种情况下管理数据库打开关闭

我有超过10个使用数据库的片段,我必须为每个片段打开关闭数据库,或者我应该在应用程序启动后打开数据库,然后在应用程序结束时关闭

如果可能那么请如何解释我

2 个答案:

答案 0 :(得分:1)

您可以简单地创建一个Singleton帮助程序,您可以在应用程序的整个生命周期中使用它,如上所述here

public class DatabaseHelper extends SQLiteOpenHelper { 

  private static DatabaseHelper sInstance;

  private static final String DATABASE_NAME = "database_name";
  private static final String DATABASE_TABLE = "table_name";
  private static final int DATABASE_VERSION = 1;

  public static DatabaseHelper getInstance(Context context) {

    // Use the application context, which will ensure that you 
    // don't accidentally leak an Activity's context.
    // See this article for more information: http://bit.ly/6LRzfx
    if (sInstance == null) {
      sInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return sInstance;
  }

  /**
   * Constructor should be private to prevent direct instantiation.
   * make call to static factory method "getInstance()" instead.
   */
  private DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
}

答案 1 :(得分:1)

是的,如果要在所有片段中打开数据库,然后在Parent Activity onCreate方法中打开它并将其关闭到OnDestroy方法,则可以按照您的要求执行此操作。

在片段中的onAttach方法中打开数据库,并在onDetach方法中关闭它...