android 在SdCard上建立資料庫

來源:互聯網
上載者:User

標籤:

 資料庫管理類中使用到的是自訂的Context,而非app的內容物件:


/** * 用於支援對儲存在SD卡上的資料庫的訪問 **/public class DbContext extends ContextWrapper {/** * 建構函式 *  * @param base *            上下文環境 */public DbContext(Context base) {super(base);}/** * 獲得資料庫路徑,如果不存在,則建立對象對象 *  * @param name * @param mode * @param factory */@Overridepublic File getDatabasePath(String name) {// 判斷是否存在sd卡boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());if (!sdExist) {// 如果不存在,Log.e("SD卡管理:", "SD卡不存在,請載入SD卡");return null;} else {// 如果存在// 擷取sd卡路徑String dbDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();dbDir += "/database";// 資料庫所在目錄String dbPath = dbDir + "/" + name;// 資料庫路徑// 判斷目錄是否存在,不存在則建立該目錄File dirFile = new File(dbDir);if (!dirFile.exists())dirFile.mkdirs();// 資料庫檔案是否建立成功boolean isFileCreateSuccess = false;// 判斷檔案是否存在,不存在則建立該檔案File dbFile = new File(dbPath);if (!dbFile.exists()) {try {isFileCreateSuccess = dbFile.createNewFile();// 建立檔案} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} elseisFileCreateSuccess = true;// 返回資料庫檔案對象if (isFileCreateSuccess)return dbFile;elsereturn null;}}/** * 重載這個方法,是用來開啟SD卡上的資料庫的,android 2.3及以下會調用這個方法。 *  * @param name * @param mode * @param factory */@Overridepublic SQLiteDatabase openOrCreateDatabase(String name, int mode,SQLiteDatabase.CursorFactory factory) {SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);return result;}/** * Android 4.0會調用此方法擷取資料庫。 *  * @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 */@Overridepublic SQLiteDatabase openOrCreateDatabase(String name, int mode,CursorFactory factory, DatabaseErrorHandler errorHandler) {SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);return result;}}



android 在SdCard上建立資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.