基于Android如何實(shí)現(xiàn)將數(shù)據(jù)庫(kù)保存到SD卡
有時(shí)候?yàn)榱诵枰瑫?huì)將數(shù)據(jù)庫(kù)保存到外部存儲(chǔ)或者SD卡中(對(duì)于這種情況可以通過(guò)加密數(shù)據(jù)來(lái)避免數(shù)據(jù)被破解),比如一個(gè)應(yīng)用支持多個(gè)數(shù)據(jù),每個(gè)數(shù)據(jù)都需要有一個(gè)對(duì)應(yīng)的數(shù)據(jù)庫(kù),并且數(shù)據(jù)庫(kù)中的信息量特別大時(shí),這顯然更應(yīng)該將數(shù)據(jù)庫(kù)保存在外部存儲(chǔ)或者SD卡中,因?yàn)镽AM的大小是有限的;其次在寫(xiě)某些測(cè)試程序時(shí)將數(shù)據(jù)庫(kù)保存在SD卡更方便查看數(shù)據(jù)庫(kù)中的內(nèi)容。
Android通過(guò)SQLiteOpenHelper創(chuàng)建數(shù)據(jù)庫(kù)時(shí)默認(rèn)是將數(shù)據(jù)庫(kù)保存在'/data/data/應(yīng)用程序名/databases'目錄下的,只需要在繼承SQLiteOpenHelper類(lèi)的構(gòu)造函數(shù)中傳入數(shù)據(jù)庫(kù)名稱(chēng)就可以了,但如果將數(shù)據(jù)庫(kù)保存到指定的路徑下面,都需要通過(guò)重寫(xiě)繼承SQLiteOpenHelper類(lèi)的構(gòu)造函數(shù)中的context,因?yàn)椋涸陂喿xSQLiteOpenHelper.java的源碼時(shí)會(huì)發(fā)現(xiàn):創(chuàng)建數(shù)據(jù)庫(kù)都是通過(guò)Context的openOrCreateDatabase方法實(shí)現(xiàn)的,如果我們需要在指定的路徑下創(chuàng)建數(shù)據(jù)庫(kù),就需要寫(xiě)一個(gè)類(lèi)繼承Context,并復(fù)寫(xiě)其openOrCreateDatabase方法,在openOrCreateDatabase方法中指定數(shù)據(jù)庫(kù)存儲(chǔ)的路徑即可,下面為類(lèi)SQLiteOpenHelper中g(shù)etWritableDatabase和getReadableDatabase方法的源碼,SQLiteOpenHelper就是通過(guò)這兩個(gè)方法來(lái)創(chuàng)建數(shù)據(jù)庫(kù)的。
/**
* Create and/or open a database that will be used for reading and writing.
* The first time this is called, the database will be opened and
* {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be
* called.
*
* <p>Once opened successfully, the database is cached, so you can
* call this method every time you need to write to the database.
* (Make sure to call {@link #close} when you no longer need the database.)
* Errors such as bad permissions or a full disk may cause this method
* to fail, but future attempts may succeed if the problem is fixed.</p>
*
* <p class="caution">Database upgrade may take a long time, you
* should not call this method from the application main thread, including
* from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
*
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null) {
if (!mDatabase.isOpen()) {
// darn! the user closed the database by calling mDatabase.close()
mDatabase = null;
} else if (!mDatabase.isReadOnly()) {
return mDatabase; // The database is already open for business
}
}
if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}
// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock. To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.
boolean success = false;
SQLiteDatabase db = null;
if (mDatabase != null) mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
db = mContext.openOrCreateDatabase(mName, 0, mFactory, mErrorHandler);
}
int version = db.getVersion();
if (version != mNewVersion) {
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
if (version > mNewVersion) {
onDowngrade(db, version, mNewVersion);
} else {
onUpgrade(db, version, mNewVersion);
}
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
onOpen(db);
success = true;
return db;
} finally {
mIsInitializing = false;
if (success) {
if (mDatabase != null) {
try { mDatabase.close(); } catch (Exception e) { }
mDatabase.unlock();
}
mDatabase = db;
} else {
if (mDatabase != null) mDatabase.unlock();
if (db != null) db.close();
}
}
}
/**
* Create and/or open a database. This will be the same object returned by
* {@link #getWritableDatabase} unless some problem, such as a full disk,
* requires the database to be opened read-only. In that case, a read-only
* database object will be returned. If the problem is fixed, a future call
* to {@link #getWritableDatabase} may succeed, in which case the read-only
* database object will be closed and the read/write object will be returned
* in the future.
*
* <p class="caution">Like {@link #getWritableDatabase}, this method may
* take a long time to return, so you should not call it from the
* application main thread, including from
* {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
*
* @throws SQLiteException if the database cannot be opened
* @return a database object valid until {@link #getWritableDatabase}
* or {@link #close} is called.
*/
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null) {
if (!mDatabase.isOpen()) {
// darn! the user closed the database by calling mDatabase.close()
mDatabase = null;
} else {
return mDatabase; // The database is already open for business
}
}
if (mIsInitializing) {
throw new IllegalStateException("getReadableDatabase called recursively");
}
try {
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null) throw e; // Can't open a temp database read-only!
Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mContext.getDatabasePath(mName).getPath();
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY,
mErrorHandler);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version " +
db.getVersion() + " to " + mNewVersion + ": " + path);
}
onOpen(db);
Log.w(TAG, "Opened " + mName + " in read-only mode");
mDatabase = db;
return mDatabase;
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase) db.close();
}
}
通過(guò)上面的分析可以寫(xiě)出一個(gè)自定義的Context類(lèi),該類(lèi)繼承Context即可,但由于Context中有除了openOrCreateDatabase方法以外的其它抽象函數(shù),所以建議使用非抽象類(lèi)ContextWrapper,該類(lèi)繼承自Context,自定義的DatabaseContext類(lèi)源碼如下:
public class DatabaseContext extends ContextWrapper {
public DatabaseContext(Context context){
super( context );
}
/**
* 獲得數(shù)據(jù)庫(kù)路徑,如果不存在,則創(chuàng)建對(duì)象對(duì)象
* @param name
* @param mode
* @param factory
*/
@Override
public File getDatabasePath(String name) {
//判斷是否存在sd卡
boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
if(!sdExist){//如果不存在,
return null;
}else{//如果存在
//獲取sd卡路徑
String dbDir= FileUtils.getFlashBPath();
dbDir += "DB";//數(shù)據(jù)庫(kù)所在目錄
String dbPath = dbDir+"/"+name;//數(shù)據(jù)庫(kù)路徑
//判斷目錄是否存在,不存在則創(chuàng)建該目錄
File dirFile = new File(dbDir);
if(!dirFile.exists()){
dirFile.mkdirs();
}
//數(shù)據(jù)庫(kù)文件是否創(chuàng)建成功
boolean isFileCreateSuccess = false;
//判斷文件是否存在,不存在則創(chuàng)建該文件
File dbFile = new File(dbPath);
if(!dbFile.exists()){
try {
isFileCreateSuccess = dbFile.createNewFile();//創(chuàng)建文件
} catch (IOException e) {
e.printStackTrace();
}
}else{
isFileCreateSuccess = true;
}
//返回?cái)?shù)據(jù)庫(kù)文件對(duì)象
if(isFileCreateSuccess){
return dbFile;
}else{
return null;
}
}
}
/**
* 重載這個(gè)方法,是用來(lái)打開(kāi)SD卡上的數(shù)據(jù)庫(kù)的,android 2.3及以下會(huì)調(diào)用這個(gè)方法。
*
* @param name
* @param mode
* @param factory
*/
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
return result;
}
/**
* Android 4.0會(huì)調(diào)用此方法獲取數(shù)據(jù)庫(kù)。
*
* @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String, int,
* android.database.sqlite.SQLiteDatabase.CursorFactory,
* android.database.DatabaseErrorHandler)
* @param name
* @param mode
* @param factory
* @param errorHandler
*/
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) {
SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
return result;
}
}
在繼承SQLiteOpenHelper的子類(lèi)的構(gòu)造函數(shù)中,用DatabaseContext的實(shí)例替代context即可:
DatabaseContext dbContext = new DatabaseContext(context); super(dbContext, mDatabaseName, null, VERSION);
基于Android如何實(shí)現(xiàn)將數(shù)據(jù)庫(kù)保存到SD卡的全部?jī)?nèi)容就給大家介紹這么多,同時(shí)也非常感謝大家一直以來(lái)對(duì)腳本之家網(wǎng)站的支持,謝謝。
相關(guān)文章
Android定時(shí)器Timer的停止和重啟實(shí)現(xiàn)代碼
本篇文章主要介紹了Android實(shí)現(xiàn)定時(shí)器Timer的停止和重啟實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
android自定義環(huán)形統(tǒng)計(jì)圖動(dòng)畫(huà)
這篇文章主要為大家詳細(xì)介紹了android自定義環(huán)形統(tǒng)計(jì)圖動(dòng)畫(huà),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07
Android自定義View實(shí)現(xiàn)左右滑動(dòng)選擇出生年份
這篇文章主要介紹了Android自定義View實(shí)現(xiàn)左右滑動(dòng)選擇出生年份,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-06-06
Recycleview實(shí)現(xiàn)無(wú)限自動(dòng)輪播
這篇文章主要為大家詳細(xì)介紹了Recycleview實(shí)現(xiàn)無(wú)限自動(dòng)輪播,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07
詳解Android使用CoordinatorLayout+AppBarLayout實(shí)現(xiàn)拉伸頂部圖片功能
這篇文章主要介紹了Android使用CoordinatorLayout+AppBarLayout實(shí)現(xiàn)拉伸頂部圖片功能,本文實(shí)例文字相結(jié)合給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10
Android實(shí)現(xiàn)登錄郵箱的自動(dòng)補(bǔ)全功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)登錄郵箱的自動(dòng)補(bǔ)全功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-04-04
clipse項(xiàng)目遷移到android studio的方法(圖文最新版)
這篇文章主要介紹了clipse項(xiàng)目遷移到android studio(圖文最新版),需要的朋友可以參考下2015-10-10
Android Studio自動(dòng)排版的兩種實(shí)現(xiàn)方式
這篇文章主要介紹了Android Studio自動(dòng)排版的兩種實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03

