Android匯入外部資料庫

來源:互聯網
上載者:User

Android匯入外部資料庫

當我們軟體中要使用大量資料,我們會選擇將這些資料存放區到一個資料庫中,然後通過資料庫的查詢修改操作來管理這些資料。大多數情況下我們都只在程式中建立使用資料庫,但也有我們在程式中只是使用的資料庫,並不在程式中建立它們,因為這種資料庫往往資料量比較大,我們在建立時如果不採用多線程和後台服務的話,很容易導致前台介面的阻塞停滯,這樣往往會影響使用者體驗,造成不好的使用效果。這時我們可不可以直接建好資料庫並錄入資料,然後通過程式將資料庫正確匯入進我們的軟體檔案夾裡面。這樣減少了讀取資料和建立資料庫的時間,可以在很大程度上提高軟體響應的速度。

還是結合之前做的一個軟體的天氣預報功能開發的執行個體來講解如何匯入外部資料庫。首先我們通過DDMS看一下資料庫的存放路徑,一般情況下資料庫的存放路徑為:/data/packagname/databases/( packagname指的是我們所建立的工程的包名,例如這裡我的包名就是com.liuproject.reminder。有的資料庫就直接在packagname下面,有的則是在databases目錄下,大家可以開啟DDMS看一下。)databases檔案夾下面有兩個資料庫:

其中City(為匯入成功後的)就是我們即將要從外部匯入的資料庫。我們將建好的City資料庫檔案拷貝到我們所建工程的assets檔案夾中,如所示:

要注意我們所提供的外部資料要和我們設計的將在軟體中使用的資料庫保持一致,及時每一條記錄的屬性值名稱和資料類型一致。資料準備完成後我們就可以開始匯入外部資料庫了。具體實現源碼如下:

 

import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;import android.os.Environment; public class ImportDB{    private final int BUFFER_SIZE = 10000;    public static final String DB_NAME = "City"; //儲存的資料庫檔案名    public static final String PACKAGE_NAME = "com.liuproject.reminder";//工程包名    public static final String DB_PATH = "/data"            + Environment.getDataDirectory().getAbsolutePath() + "/"            + PACKAGE_NAME+"/databases";  //在手機裡存放資料庫的位置private Context context;    ImportDB(Context context) {        this.context = context;    }       public void copyDatabase() {             String dbfile=DB_PATH + "/" + DB_NAME ;        try {           //執行資料庫匯入                InputStream is = this.context.getResources().getAssets().open("City"); //欲匯入的資料庫                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();//關閉輸入資料流        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }     }}通過上面的這個class我們就可以將存放在assets檔案夾中的外部資料庫匯入到我們所需要的檔案目錄下。接著開始建立我們在程式中所要使用的資料庫類,如下代碼:class CityDB extends SQLiteOpenHelper{//城市Id資料庫操作         private final String DB_NAME="CityID";//資料庫名稱          public CityDB(Context context,String name,CursorFactory factory,int version) {                   super(context, name,factory, version);          }          @Override         public void onCreate(SQLiteDatabase db) {                                 String createDB= "create table "+DB_NAME+"(cityid varchar(14) primary key , cityname varchar(20),type int)";//資料庫中記錄的屬性名稱及屬性值類型                    db.execSQL(createDB);//建立資料庫         }          @Override         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {                     String dropTableSQL = "DROP TABLE IF EXISTS "  + DB_NAME + " ";                     db.execSQL(dropTableSQL);                     dropTableSQL = "DROP TABLE IF EXISTS " + DB_NAME   + " ";                     db.execSQL(dropTableSQL);                     onCreate(db);              }                   public void execSQL(String sql, Object[] args) {//執行操作                   SQLiteDatabase db = this.getWritableDatabase();                   db.execSQL(sql, args);         }          public Cursor query(String sql, String[] args) {//返回操作結果指標                   SQLiteDatabase db = this.getWritableDatabase();                   Cursor cursor = db.rawQuery(sql, args);                   return cursor;         }}
在之後的程式中我們就可以通過new CityDB(this, NAME, null, VERSION);來建立一個資料庫操作輔助對象,其中的NAME要與我們之間匯入的外部資料庫名稱一致,在我的例子裡面NAME=“City”,VERSION為資料庫的版本號碼,盡量保持與前面建立時的一致性。在程式合適的位置使用ImportDB類的copyDatabase()方法將資料庫匯入。如果資料庫比較大可以在後台開線程進行操作。

聯繫我們

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