我們平時見到的android資料庫操作一般都是在程式開始時建立一個空的資料庫,然後再進行相關操作。如果我們需要使用一個已有資料的資料庫怎麼辦呢?
我們都知道android系統下資料庫應該存放在 /data/data/com.*.*(package name)/ 目錄下,所以我們需要做的是把已有的資料庫傳入那個目錄下。操作方法是用FileInputStream讀取原資料庫,再用FileOutputStream把讀取到的東西寫入到那個目錄。
操作方法:1. 把原資料庫包括在項目源碼的 res/raw 目錄下,然後建立一個DBManager類,代碼如下:
package com.android.ImportDatabase;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.os.Environment;import android.util.Log;public class DBManager {private final int BUFFER_SIZE = 400000;public static final String DB_NAME = "countries.db"; //儲存的資料庫檔案名public static final String PACKAGE_NAME = "com.android.ImportDatabase";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.countries); //欲匯入的資料庫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;}
//do something else here
public void closeDatabase() {this.database.close();}}
然後在程式的首個Activity中樣本化一個DBManager對象,然後對其執行openDatabase方法就可以完成匯入了,可以把一些要對資料庫進行的操作寫在DBManager類裡,然後通過DBManager類的對象調用;也可以在完成匯入之後通過一個SQliteDatabase類的對象開啟資料庫,並執行操作。
我的做法是 在程式的首個Activity中匯入資料庫:
package com.android.ImportDatabase;import android.app.Activity;import android.content.Intent;import android.os.Bundle;public class RootView extends Activity {public DBManager dbHelper;
@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);dbHelper = new DBManager(this);dbHelper.openDatabase();dbHelper.closeDatabase();}}
此時在DDMS中可以查看到,外部資料庫已經成功匯入
在需要使用資料庫的類裡:
package com.android.ImportDatabase;import java.util.ArrayList;import android.app.Activity;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;public class TaxiActivity extends Activity {private SQLiteDatabase database; ArrayList<CityClass> CITY;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null);CITY = getCity(); // do something with CITYdatabase.close();}private ArrayList<CityClass> getCity() {Cursor cur = database.rawQuery("SELECT city.id_city, city.name FROM taxi, city WHERE city.id_city = taxi.id_city GROUP BY city.id_city", null);if (cur != null) {int NUM_CITY = cur.getCount();ArrayList<CityClass> taxicity = new ArrayList<CityClass>(NUM_CITY);if (cur.moveToFirst()) {do {String name = cur.getString(cur.getColumnIndex("name"));int id = cur.getInt(cur.getColumnIndex("id_city"));CityClass city = new CityClass("", 0);System.out.println(name); //額外添加一句,把select到的資訊輸出到Logcatcity.city_name = name;city.city_id = id;taxicity.add(city);} while (cur.moveToNext());}return taxicity;} else {return null;}}}
查看輸出的結果:
如果匯入的資料庫大小有問題,或使用InputStream讀取出錯了,請看此貼 [iPhone/Android] 匯入程式的資料庫大小與原資料庫大小不一致怎麼辦?