【问题标题】:Initializing a SQLite database初始化 SQLite 数据库
【发布时间】:2018-02-05 08:19:25
【问题描述】:

DatabaseHelper 类的 onCreate 方法在调用 db.getWritableDatabase() 或 db.getReadableDatabase() 时被调用。所以,每当第一次使用 dbhelper 时,onCreate 都会在那个时候被调用。
我希望在第一次启动应用程序时调用我的数据库,而不是第一次使用 dbhelper。

【问题讨论】:

  • 是什么阻止你打电话,例如getWritableDatabase() 应用何时启动?

标签: android database sqlite oncreate


【解决方案1】:

在应用程序类中初始化您的 Db 类 ....

public class AppController extends Application {

    private static AppController mInstance;
    private DatabaseManager databaseManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

        databaseManager = new DataBaseManger(mInstance);


    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

}

在 Android Manifest 中声明应用程序类...

<application
        android:name=".app.AppController"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

     ---------------------------------------
     ----------------------------------------
   -------------------------------------------

   </application>

【讨论】:

  • public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = 上下文; } 这不会调用 onCreate() 方法
【解决方案2】:

我希望在第一次启动应用程序时调用我的数据库,而不是第一次使用 dbhelper。

创建一个自定义应用程序类并在应用程序的onCreate() 方法中初始化您的数据库。这将确保在任何Activity 启动之前初始化您的数据库。因为 Application 类在任何 Activity 启动之前运行。

public class MyApplication extends Application {
  public void onCreate() {
    super.onCreate();
    // Initialize your Database here 

  }
}

AndroidManifest.xml中定义你的应用程序类

    <application
    android:name="com.example.MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/BaseTheme">
    ...................
    ...................
     </application>

【讨论】:

  • 我应该添加这个代码吗?,DatabaseHandler db = new DatabaseHandler(getApplicationContext()); db.getWritableDatabase();
  • 拨打DatabaseHandler db = new DatabaseHandler(getApplicationContext());
  • 但这不会调用dbhelper的oncreate方法
  • public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = 上下文; }
猜你喜欢
  • 2021-11-10
  • 1970-01-01
  • 2012-12-15
  • 2017-05-11
  • 1970-01-01
  • 2020-11-20
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多