android 数据库实例,android – 数据库全局实例
當我剛開始使用Android時,這對我來說是一個問題,因為網(wǎng)上沒有很多教程描述如何正確地允許在整個應用程序中訪問您的數(shù)據(jù)庫(不要問我原因).這里有一些展示三種可能方法的示例代碼.
方法#1:繼承`Application`
如果您知道您的應用程序不會非常復雜(例如,如果您知道您最終只有一個Application類的子類),那么您可以創(chuàng)建Application的子類并讓您的主Activity擴展它.這可確保數(shù)據(jù)庫的一個實例在整個應用程序的整個生命周期中運行.
public class MainApplication extends Application {
/**
* see NotePad tutorial for an example implementation of DataDbAdapter
*/
private static DataDbAdapter mDbHelper;
/**
* create the database helper when the application is launched
*/
@Override
public void onCreate() {
mDbHelper = new DataDbAdapter(this);
mDbHelper.open();
}
/**
* close the database helper when the application terminates.
*/
@Override
public void onTerminate() {
mDbHelper.close();
mDbHelper = null;
}
public static DataDbAdapter getDatabaseHelper() {
return mDbHelper;
}
}
方法#2:讓`SQLiteOpenHelper`成為靜態(tài)數(shù)據(jù)成員
這不是完整的實現(xiàn),但它應該讓您對如何正確設計DatabaseHelper類有所了解.靜態(tài)工廠方法確保任何時候只存在一個DatabaseHelper實例.
/**
* create custom DatabaseHelper class that extends SQLiteOpenHelper
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper mInstance = null;
private static final String DATABASE_NAME = "databaseName";
private static final String DATABASE_TABLE = "tableName";
private static final int DATABASE_VERSION = 1;
private Context mCxt;
public static DatabaseHelper getInstance(Context ctx) {
/**
* use the application context as suggested by CommonsWare.
* this will ensure that you dont accidentally leak an Activitys
* context (see this article for more information:
* http://developer.android.com/resources/articles/avoiding-memory-leaks.html)
*/
if (mInstance == null) {
mInstance = new DatabaseHelper(ctx.getApplicationContext());
}
return mInstance;
}
/**
* constructor should be private to prevent direct instantiation.
* make call to static factory method "getInstance()" instead.
*/
private DatabaseHelper(Context ctx) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mCtx = ctx;
}
}
方法#3:使用`ContentProvider`抽象SQLite數(shù)據(jù)庫
這是我建議的方法.首先,新的LoaderManager類在很大程度上依賴于ContentProviders,因此如果您希望Activity或Fragment實現(xiàn)LoaderManager.LoaderCallbacks< Cursor> (我建議你利用它,這很神奇!),你需要為你的應用程序實現(xiàn)一個ContentProvider.此外,您不必擔心使用ContentProviders創(chuàng)建Singleton數(shù)據(jù)庫幫助程序.只需從Activity中調用getContentResolver(),系統(tǒng)就會為您處理所有事情(換句話說,不需要設計Singleton模式來防止創(chuàng)建多個實例).
希望有所幫助!
總結
以上是生活随笔為你收集整理的android 数据库实例,android – 数据库全局实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果官网新设计:采用新的下拉式导航菜单
- 下一篇: 数据库关机_数据库:MySQL常见的三种