简体   繁体   English

Android项目生命周期 - 活动生命周期之前(Activity.onCreate())

[英]Android Project Lifecycle - before Activity Lifecycle ( Activity.onCreate() )

I'm looking to implement a SQLite database in an Android project that I'm currently working on. 我正在寻找在我正在开发的Android项目中实现SQLite数据库。 To my surprise, it appears the only way to create this, is in the Activity code itself. 令我惊讶的是,似乎创建它的唯一方法是在Activity代码本身。 (My last experience with Java and local databases was with Derby, which was a local file I had not created within the code.) (我对Java和本地数据库的最后一次经历是使用Derby,这是我在代码中没有创建的本地文件。)

My question is, is there anything I can tap into that happens before the first Activity's onCreate()? 我的问题是, 在第一个Activity的onCreate()之前有什么我可以利用的吗? I'll relate this back to Windows Form applications, where you can access Main() before launching the Form (Activity equivalent). 我将它与Windows窗体应用程序联系起来,您可以在启动窗体(活动等效项)之前访问Main()。

If I have to create the database within the program's code, I want to check to see if it already exists, only once, before the Activities start. 如果我必须在程序代码中创建数据库,我想在活动开始之前检查它是否已经存在,只有一次。

There is, but you don't need to. 有,但你不需要。 SQLite databases (which are built into Android) are just files on the local filesystem. SQLite数据库(内置于Android中)只是本地文件系统上的文件。 Now you generally access them through either an ORM layer or through SQliteOpenHelper, which are Java interfaces to the database. 现在,您通常通过ORM层或通过SQliteOpenHelper访问它们,它们是数据库的Java接口。 When you open it, you just tell it where the file is. 当你打开它时,你只需告诉它文件的位置。 Generally you have a Singleton of the open helper or ORM layer class, so no per-Activity setup- you just throw any of that you need in the constructor there, and let the Singleton take care of it in whatever Activity ends up creating it. 通常你有一个单独的open helper或ORM层类,所以没有per-Activity设置 - 你只需要在构造函数中抛出你需要的任何东西,并让Singleton在任何Activity最终创建它时处理它。

The recommended way of using a database is to use SQLiteOpenHelper , which automatically creates it the first time you try to access it. 建议使用数据库的方法是使用SQLiteOpenHelper ,它会在您第一次尝试访问它时自动创建它。 (And also handles updates.) (还处理更新。)

您可以使用Application的onCreate方法在应用程序启动时(即在任何Activity之前)运行任何代码。

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

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