Android SQLite database shared between activities
You could do this implementing a BaseActivity class what is extended by all Activity classes in the application:
public class BaseActivity extends Activity {
protected static SQLiteOpenHelper database;
@Override
protected void onPause() {
// TODO close database
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
// TODO open database
}
}
public class OneSubActitivy extends BaseActivity {
// methods using database from BaseActivity
}
Create an Application class for your app. This will remain active in memory for as long as any part of your App is running. You can create your DB from the onCreate method and clean it up in the onTerminate method. (Note that there is no guarantee that onTerminate will be called, so you should be careful about what you depend upon here. However, since a SQLite database is just a file, and is agressively flushed, the close operation is a courtesy more than a necessity.)
You can access the application from any Activity via "getApplication", so the DB will always be available to you.
For more info, see http://developer.android.com/guide/appendix/faq/framework.html#3.
Update:
As requested, here's an example of using getApplication. It's really incredibly simple.
SQLiteDatabase mDB;
@Override protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDB = ((MyApplication)getApplication()).mDB;
}
If every activity includes this code, then every activity will have its own mDB field which references the same underlying shared DB object.