日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

android 数据库实例,android – 数据库全局实例

發(fā)布時間:2023/12/15 数据库 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android 数据库实例,android – 数据库全局实例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

當我剛開始使用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 – 数据库全局实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。