初始化 SQLite 数据库

Initializing a SQLite database

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

I want my database to be called whenever the app is started for the first time instead of first use of dbhelper.

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

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

  }
}

AndroidManifest.xml

中定义您的应用程序 Class
    <application
    android:name="com.example.MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/BaseTheme">
    ...................
    ...................
     </application>

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

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 清单中声明应用程序 Class...

<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>