在Android程式中使用已有的SQLite資料庫,androidsqlite

來源:互聯網
上載者:User

在Android程式中使用已有的SQLite資料庫,androidsqlite

    在中文搜尋中,沒有找到一篇比較好的關於如何在Android應用中使用自己事先建立好的資料庫的文章,於是在Google上找到這篇英文文章,按照它的步驟,測試成功,決定把這篇文章大致的翻譯一下,想看原文的可以點擊這裡:http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ ,這篇文章有700多條評論,所以應該還是經曆過比較多的討論的。在overstack的一些解答中,也是直接引用了這篇文章。分享給有需要的同學。


譯文:

    在大多數的Android樣本或是教程中,都是假設你需要在程式啟動並執行時候建立一個資料庫並插入新的資料,而不是使用一個獨立的提前讀取的資料庫。

    這裡要講到的是,如何使用你自己的儲存在“assets”檔案夾下的SQLite資料庫,即怎樣將你準備好的資料庫複寫到你Android程式的系統資料庫路徑下,從而讓SQLiteDatabase API能夠正常的讀取它。

  1. 準備SQLite database檔案

    假設你已經建立了一個sqlite資料庫,我們需要對其進行一些修改。

   (譯者註:這裡原文是推薦了一個SQLite資料庫管理軟體,這個我覺得可以隨自己的喜好,最Windows下面有多款可視化的SQlite資料庫管理軟體,可以方便的讀取,編輯資料庫,例如我用的是sqlitestudio

開啟資料庫,添加一個新的table “android_metadata",插入一行資料,具體的SQL如下:

CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')INSERT INTO "android_metadata" VALUES ('en_US')
   (譯者註:上面兩行是表明需要進行的操作,具體可以直接在sqlitesstudio中完成)

    然後你需要對你資料表格的primary id 列重新命名為 “_id”,這樣Adroid會知道怎麼對id列進行綁定,你可以很容易的在SQlite資料庫管理軟體中進行列編輯。

    這兩步之後,你的sqlite資料庫檔案就準備好了。

  (譯者註:這裡我保留了id列,即沒有對其進行重新命名,測試證明也是沒有問題的)


2. 在你的Android程式中複製,開啟以及訪問資料庫

    現在把你上一步準備好的資料庫檔案放在“assets”檔案夾下面,然後通過繼承 SQLiteOpenHelper類來建立一個Database Helper類,

你的DataBaseHelper類大致可以如下:

public class DataBaseHelper extends SQLiteOpenHelper{     //The Android's default system path of your application database.    private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";     private static String DB_NAME = "myDBName";     private SQLiteDatabase myDataBase;      private final Context myContext;     /**     * Constructor     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.     * @param context     */    public DataBaseHelper(Context context) {     super(context, DB_NAME, null, 1);        this.myContext = context;    }   /**     * Creates a empty database on the system and rewrites it with your own database.     * */    public void createDataBase() throws IOException{     boolean dbExist = checkDataBase();     if(dbExist){    //do nothing - database already exist    }else{     //By calling this method and empty database will be created into the default system path               //of your application so we are gonna be able to overwrite that database with our database.        this.getReadableDatabase();         try {     copyDataBase();     } catch (IOException e) {         throw new Error("Error copying database");         }    }     }     /**     * Check if the database already exist to avoid re-copying the file each time you open the application.     * @return true if it exists, false if it doesn't     */    private boolean checkDataBase(){     SQLiteDatabase checkDB = null;     try{    String myPath = DB_PATH + DB_NAME;    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);     }catch(SQLiteException e){     //database does't exist yet.     }     if(checkDB != null){     checkDB.close();     }     return checkDB != null ? true : false;    }     /**     * Copies your database from your local assets-folder to the just created empty database in the     * system folder, from where it can be accessed and handled.     * This is done by transfering bytestream.     * */    private void copyDataBase() throws IOException{     //Open your local db as the input stream    InputStream myInput = myContext.getAssets().open(DB_NAME);     // Path to the just created empty db    String outFileName = DB_PATH + DB_NAME;     //Open the empty db as the output stream    OutputStream myOutput = new FileOutputStream(outFileName);     //transfer bytes from the inputfile to the outputfile    byte[] buffer = new byte[1024];    int length;    while ((length = myInput.read(buffer))>0){    myOutput.write(buffer, 0, length);    }     //Close the streams    myOutput.flush();    myOutput.close();    myInput.close();     }     public void openDataBase() throws SQLException{     //Open the database        String myPath = DB_PATH + DB_NAME;    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);     }     @Overridepublic synchronized void close() {         if(myDataBase != null)        myDataBase.close();         super.close(); } @Overridepublic void onCreate(SQLiteDatabase db) { } @Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }         // Add your public helper methods to access and get content from the database.       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy       // to you to create adapters for your views. }

    就這樣。

    現在你可以建立一個新的DataBaseHelper執行個體,然後調用createDataBase(),然後再調用openDataBase()方法,記住修改DB_PATH字串中“YOUR_PACKAGE”為你真正的package名稱(也就是說com.examplename.myapp)

以下是示範代碼:

 ...         DataBaseHelper myDbHelper = new DataBaseHelper();        myDbHelper = new DataBaseHelper(this);         try {         myDbHelper.createDataBase();  } catch (IOException ioe) {  throw new Error("Unable to create database");  }  try {  myDbHelper.openDataBase();  }catch(SQLException sqle){  throw sqle;  }         ...




android 開發 怎訪問外部SQLite 資料庫 就是其他應用程式的資料庫 最好有詳細說明與代碼

這個裡面都有說明的 你好好看看 希望可以幫到伱

www.ibm.com/...qlite/
 
android開發中使用資料庫SQLite的時,怎才可以在安卓程式退出後,再次使用程式的時可以在使用第一次建立的

openOrCreateDatabase 是開啟或者建立資料庫,如果資料庫已經存在了,會使用已存在的
 

聯繫我們

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