Android Sqlite 数据初始化
生活随笔
收集整理的這篇文章主要介紹了
Android Sqlite 数据初始化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
android系統下每個程序的數據存放在 /data/data/(package name)/ 目錄下,數據庫則是在/dababases/目錄下..
所以,你只要用FileInputStream讀取原數據庫,再用FileOutputStream把讀取到的東西寫入到那個目錄就可以了..
操作方法:1. 把原數據庫包括在項目源碼的 res/raw 目錄下.
2.創建一個類來控制database..如下:
?
public?class?DatabaseManager{????????private?final?int?BUFFER_SIZE?=?400000;
????????public?static?final?String?DB_NAME?=?"myDatabase.db";?//保存的數據庫文件名
????????public?static?final?String?PACKAGE_NAME?=?"com.android.ImportDBTest";//包名
????????public?static?final?String?DB_PATH?=?"/data"
????????????????????????+?Environment.getDataDirectory().getAbsolutePath()?+?"/"
????????????????????????+?PACKAGE_NAME;??//在手機里存放數據庫的位置
????????private?SQLiteDatabase?database;
????????private?Context?context;
????????DBManager(Context?context)?{
????????????????this.context?=?context;
????????}
????????public?void?openDatabase()?{
????????????????this.database?=?this.openDatabase(DB_PATH?+?"/"?+?DB_NAME);
????????}
????????private?SQLiteDatabase?openDatabase(String?dbfile)?{
????????????????try?{
????????????????????????if?(!(new?File(dbfile).exists()))?{ //判斷數據庫文件是否存在,若不存在則執行導入,否則直接打開數據庫
????????????????????????????????InputStream?is?=?this.context.getResources().openRawResource(
????????????????????????????????????????????????R.raw.myDatabase);?//欲導入的數據庫
????????????????????????????????FileOutputStream?fos?=?new?FileOutputStream(dbfile);
????????????????????????????????byte[]?buffer?=?new?byte[BUFFER_SIZE];
????????????????????????????????int?count?=?0;
????????????????????????????????while?((count?=?is.read(buffer))?>?0)?{
????????????????????????????????????????fos.write(buffer,?0,?count);
????????????????????????????????}
????????????????????????????????fos.close();
????????????????????????????????is.close();
????????????????????????}
????????????????????????SQLiteDatabase?db?=?SQLiteDatabase.openOrCreateDatabase(dbfile,
????????????????????????????????????????null);
????????????????????????return?db;
????????????????}?catch?(FileNotFoundException?e)?{
????????????????????????Log.e("Database",?"File?not?found");
????????????????????????e.printStackTrace();
????????????????}?catch?(IOException?e)?{
????????????????????????Log.e("Database",?"IO?exception");
????????????????????????e.printStackTrace();
????????????????}
????????????????return?null;
}
?
然后在需要用到數據庫的時候,用實例化一個DatabaseManager類,調用其openDatabase方法就可以返回一個SQLiteDatabase對象了..如下:
?
SQLiteDatabase?db?=?new?DBManager(this).openDatabase();?
轉載于:https://www.cnblogs.com/yingql/archive/2011/12/12/2284841.html
總結
以上是生活随笔為你收集整理的Android Sqlite 数据初始化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《Effective Java》 第一讲
- 下一篇: Android隐藏标题栏,全屏显示