android 資料庫建立在SD(TF)卡中

來源:互聯網
上載者:User

android 應用建資料庫時,預設建立在 系統內 /data/data/'應用程式套件名'/

有時我們需要建在SD卡當中。

在SD卡的優點:

1 當系統復原出廠設定等操作後,重新安裝應用。資料不會丟失。

2 方便備份、恢複。只要複製到PC上,或從PC複製到Android裝置的SD卡中即可。

等等。

怎樣才能方便的將資料庫移動至SD卡?

1 初始化,SD卡路徑。定義資料庫所在路徑。

package cn.hpc.dbdemo;import java.io.File;import android.os.Environment;/**資料庫根目錄 /sdcard/hpcDbData/應用的資料建立在 /sdcard/hpcDbData/'包名'/*/public class SDBHelper {public static final String DB_DIR = Environment.getExternalStorageDirectory().getPath()+ File.separator + "hpcDbData" + File.separator+ SDBHelper.class.getPackage().getName();static {while(! Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();break;}}File dbFolder = new File(DB_DIR);// 目錄不存在則自動建立目錄if (!dbFolder.exists()){dbFolder.mkdirs();}}}

2  SQLiteOpenHelper 中的使用方法。

mDbName 資料庫名,帶全路徑

package cn.hpc.dbdemo;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;public class DemoDbh extends SQLiteOpenHelper {public static final int VERSION = 1;public static final String mDbName =  SDBHelper.DB_DIR + File.separator + "demo.db";public DemoDbh(Context context) {super(context, mDbName, null, VERSION);}// ... 其它的省略,減少版面佔用}

非常簡單。

完畢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.